Not getting right output for natural log formula - java

I'm trying to get my program to out the first 500 values for this formula: -12*ln(1-x) where x is the return of double next(). I don't know what I'm doing wrong because I can't get the right output. The random number uses this formula x(i+1) = (a * x(i) + c) mod k
public class myRnd {
// Linear values for x(i+1) = (a * x(i) + c) % k
final static int a = 7893;
final static int c = 3517;
final static int k = 8192;
// Current value for returning
int x;
int y;
int z;
public myRnd() {
// Constructor simply sets value to half of k
x = (125*k) /1024;
//y = (125*k) /1024;
}
double next() {
// Calculate next value in sequence
x = (a * x + c) % k;
// Return its 0 to 1 value
return (double)x / k;
}
public static void main(String[] args) {
int situation;
double sec_answer;
// Create a new myRnd instance
myRnd r = new myRnd();
// Output 53 random numbers from it
for (int i = 0; i < 53; i++) {
System.out.println (r.next());
}
System.out.println("random variable");
for(int b = 0; b < 500; b++){
sec_answer = (-12)*Math.log(1- r.next());
System.out.println(sec_answer);
}
}
}

I suppose these are the first 5 values you're expecting from your program in each loop!
0.9302978515625
0.270263671875
0.6204833984375
0.90478515625
0.8985595703125
random variable
31.962289651479345
3.78086405322487
11.626283246646423
28.21943313114782
27.45940262908609
In your main method you have only one instance of the class:
// Create a new myRnd instance
myRnd r = new myRnd();
This initialization is propagated to both for loops.
Simple Solution: Add another instance / initialization of myRnd for the second for loop, as an example you could reuse the same variable as r = new myRnd(); before the second loop.

Related

math.sqrt gives me incorrect result (double)

I am writing a program that prints 100 random coordinates within a circle. The circle has the radius 10 and its center is located at (0,0). However, some of the coordinates y:value is incorrectly calculated when I'm using: y = Math.sqrt(100 -x^2) The result is like off... Why is that ? (See picture) For positive y:values, they get too big sometimes and its because of the math.sqrt calculation with doubles.
package RKap14;
import ZindansMethods.ZindanRandom;
public class Dot {
public double x;
public double y;
public static void main(String[] arg)throws Exception {
//Create the array with null fields?
Coord[] c;
//Decide how many fields
c = new Coord[100];
//Create an object of class Coord in each slot of the array
for(int i = 0; i<c.length; i++) {
c[i] = new Coord();
}
//Assign random coordinates for each field x & y
for(int i = 0; i<c.length; i++) {
c[i].x = ZindanRandom.randomized(-10,10);
//Since sometimes Java calculates wrong and gives numbers above 10 and below -10...
while(c[i].x > 10 || c[i].x < -10)
c[i].x = ZindanRandom.randomized(-10,10);
c[i].y = ZindanRandom.randomized(-Math.sqrt(100-c[i].x*c[i].x), Math.sqrt(100-c[i].x*c[i].x));
}
//Print out the coordinates in form: (x,y),(x1,y1)...(x99,y99)
for (int i = 0; i<c.length; i++) {
System.out.print("(" + c[i].x + "," + c[i].y + ")" + ",");
}
}
}
class Coord {
double x;
double y;
}
The random method I am using:
//Gives random number a to b. For example -10 <= x <= 10
public static double randomized (double a, double b) {
return (a-1+Math.random()*Math.abs(b-a+1)+1);
}
I don't know what to try. I tried doing this program with a trigonometric approach but I'd rather understand why the calculator is doing its job wrongfully. Are there too many decimals? Can I do something about it ?
Circle test
your random function is generating numbers outside the given range
for example if you substitute the values into your equation and and use 1 as the value returned from Math.random() you will get 101.
Try the following random function instead:
public static double randomized(double min, double max)
return Math.random() * (max - min) + min;
}

Using a method to create an array then using that array in the main method

I'm trying to use this array I create in printGrid method throughout my program. Currently, I have to run this method, but the values change because of the math.random method nested in this method and I don't want it to. I just want to run this once and use the output throughout my method, is this possible?
What I've tried - I've tried to return the value of the mapArray (seen in code) and printing that out, I'm having issue with that. I've also tried isolating the math.random method in it's own method to calculate the value of the cookies, but my issue with that is that it only returns one value and I need a dynamic amount depending on the input of the x / y vars. Any suggestions?
public static char[][] printGrid(int x, int y) {
// int [][] mapArray = new int [x][y]; // Gets the information to print the array
mapArray = new char[x][y]; // Gets the information to print the array
double cookies = (x * y) * (.1); // Calculates the number of cookies per x / y input
// Storing '.' in all values of the array
for (int d = 0; d < x; d++) // Moved from below.
{
for (int j = 0; j < y; j++) {
mapArray[d][j] = '.';
}
System.out.println();
}
// Storing '0' in random values of the array and '<' at [0][0]
int c = 0;
for (c = 1; c <= cookies; c++) {
int cookiesPrintColumn = (int)(cookies * Math.random());
int cookiesPrintRow = (int)(cookies * Math.random());
mapArray[cookiesPrintColumn][cookiesPrintRow] = 'O';
mapArray[0][0] = '>';
}
// Copy loop from above to print the grid.
for (int d = 0; d < x; d++) {
for (int j = 0; j < y; j++) {
System.out.print(mapArray[d][j]);
return mapArray;
}
System.out.println();
}
return mapArray;
} // printGrid method close
If you are trying to create an array in a method, and then need to use in throughout your program, such as in main, you aren't going to be able to directly use that exact array because it will be out of scope. You can however create and then initialize the array in main equal to the return statement of your method. For example:
main() {
int[][] example;
example[][] = method(...);
}
int [][] method(...){
int[][] exampleArray = {1,2,3} // your random values here
return exampleArray;
}
Because you are creating the actual array inside of the method, it will not be in scope in main. This however will have the exact values the same, so the random numbers will be identical, and you can continue to use this for the rest of your program.
Use return value:
import package.ClassNane;
class Example {
int x = 1;
int y = 2;
char[][] grid = ClassName.printGrid(x, y);
}

How to create an array with a random amount of values

I need to create an array that has a random amount of values from 8 to 12, but it says my variable is incompatible. What do I have to change? Should x not be an int?
Here is the first part of the code that includes the problem:
public class Fish {
int min = 8;
int max = 12;
int x = min + (int)(Math.random() * ((max-min) + 1));
static Fish[] myFish = new Fish[x];
static int Fcount=0;
private float weight;
public Fish(float w) { weight = w;
myFish[Fcount] = this;
Fcount++;
}
public float getWeight( ) { return weight; } }
The second part of my code is:
public class GoFish {
public static void main(String[] args) {
float[] myWeights;
for (int i = 0 ; i < x ; i++){
int min = 1;
int max = 20;
myWeights[i] = min + (int)(Math.random() * ((max-min) + 1));
}
for ( float w : myWeights ) { new Fish(w); }
for ( Fish f : Fish.myFish ) {
System.out.println( f.getWeight() );
} } }
Could you also explain the problem, because I would like to understand what I'm doing wrong. I also have to make the weight a random number between 1 and 20, but I can't get this type of random numbers to work.
Edit: Since we are making the x variable static, how do I use it in the other file? because I need the array values to be random.
x is an instance variable. You're trying to access (javac compiler would say "reference") instance variable (javac would say "non-static variable") from a static context (javac would say the same thing). This won't compile because during the static Fish[] myFish = new Fish[x]; there is no any Fish instance.
You can change your code to:
static int min = 8;
static int max = 12;
static int x = min + (int)(Math.random() * ((max-min) + 1));
This will make non-static variable x static.
Here's the official explanation of static variables (officials prefer to call them class variables).

Using loops to compute factorial numbers, Java

I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */

how to assign random number with range to 2D array dimensions

In main, assign 2 random numbers (ints between 3 and 10) for the first dimension and the second dimension
I had this but the Math.random() method doesn;t work
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
double doubMatrix1[][] = (int) (Math.random()*(10-3+1)+3);
double doubMatrix2[][];
double doubMatrix3[][];
}
}
The problem in your code is that you are trying to initialize a matrix of double with an int
Types must be equals!
Here are your code fixed.
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
int d1 = (int) (Math.random()*(10-3+1)+3);
int d2 = (int) (Math.random()*(10-3+1)+3);
double doubMatrix1[][] = new double[d1][d2];
double doubMatrix2[][];
double doubMatrix3[][];
}
}
hope this help
To create a multidimensional array in Java, use new <type>[dim1][dim2], as in the following code:
Random rand = new Random();
int r1 = rand.nextInt(8) + 3;
int r2 = rand.nextInt(8) + 3;
double doubMatrix[][] = new double[r1][r2];
Math.random() returns fraction between 0.0 and 1.0. So with (int) (Math.random()*(10-3+1)+3) you are getting only one random number between 3 and 10 inclusive. But you are assigning it to double doubMatrix1[][]. So probably you are calling constructor in wrong way. You are supposed to generate two distinct random number r1, r2 according to the method taught by your teacher then call constructor like double doubMatrix1[][] = double[r1][r2]
check this out, this might be helpful:
// DMA of 2D array in C++
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x = 3, y = 3;
int **ptr = new int *[x];
for(int i = 0; i<y; i++)
{
ptr[i] = new int[y];
}
srand(time(0));
for(int j = 0; j<x; j++)
{
for(int k = 0; k<y; k++)
{
int a = rand()%5;
ptr[j][k] = a;
cout<<ptr[j][k]<<" ";
}
cout<<endl;
}
}
we used a pointer and deal it just like 2D array here, use % for limit

Categories

Resources