math.random 在循环中生成相同的数字
math.random in loop generating same number
我试图通过在 -1 和 1 之间给定随机生成的 x 和 y 点时找到方形与圆形的比率来复制 monte carlo 模拟。
我在为 x 和 y 生成随机数时遇到问题,因为它们 return
每个循环的值相同。
import java.util.Scanner;
public class monte
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int loop_n = input.nextInt();
//true false switch for the while loop
boolean t_f = true;
int count = 0; //counts how many iterations until inside the circle
double radius = 0; //calculates the pythagoras c from x, y coordinates
double x = 0, y = 0;
int i;
for (i = 0; i < loop_n; i++)
{
while(t_f) //while loop to see if the c from x,y coordinates is smaller than 1
{
x = -1 + (Math.random() * (2));
y = -1 + (Math.random() * (2));
radius = Math.pow((Math.pow(x, 2.0)) + Math.pow(y, 2.0), 0.5);
if (radius < 1) //terminates while loop if radius is smaller than 1
{ //thus being inside the circle
t_f = false;
}
count++;
}
System.out.println("" + radius);
System.out.println("" + count);
}
}
}
命令的结果:
Math.Random内循环是否有一定规律?还是我的代码写错了?
我怀疑 Math.random()
工作不正常。您的循环逻辑完全关闭。一旦你设置 t_f = false;
一次,你将始终打印相同的半径,因为你再也不会进入 while
循环。因此,您应该更改代码以在打印 radius
和 count
.
后设置 t_f = true;
或者完全放弃 t_f
并使用 break;
。
您将 t_f 设置为 false,只有 i=0 的迭代才真正起作用。所有其他迭代只打印你的半径和计数,它们保持不变。我假设您想在 while(t_f) 循环之前将 t_f 设置为 true。
我试图通过在 -1 和 1 之间给定随机生成的 x 和 y 点时找到方形与圆形的比率来复制 monte carlo 模拟。 我在为 x 和 y 生成随机数时遇到问题,因为它们 return 每个循环的值相同。
import java.util.Scanner;
public class monte
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int loop_n = input.nextInt();
//true false switch for the while loop
boolean t_f = true;
int count = 0; //counts how many iterations until inside the circle
double radius = 0; //calculates the pythagoras c from x, y coordinates
double x = 0, y = 0;
int i;
for (i = 0; i < loop_n; i++)
{
while(t_f) //while loop to see if the c from x,y coordinates is smaller than 1
{
x = -1 + (Math.random() * (2));
y = -1 + (Math.random() * (2));
radius = Math.pow((Math.pow(x, 2.0)) + Math.pow(y, 2.0), 0.5);
if (radius < 1) //terminates while loop if radius is smaller than 1
{ //thus being inside the circle
t_f = false;
}
count++;
}
System.out.println("" + radius);
System.out.println("" + count);
}
}
}
命令的结果:
Math.Random内循环是否有一定规律?还是我的代码写错了?
我怀疑 Math.random()
工作不正常。您的循环逻辑完全关闭。一旦你设置 t_f = false;
一次,你将始终打印相同的半径,因为你再也不会进入 while
循环。因此,您应该更改代码以在打印 radius
和 count
.
t_f = true;
或者完全放弃 t_f
并使用 break;
。
您将 t_f 设置为 false,只有 i=0 的迭代才真正起作用。所有其他迭代只打印你的半径和计数,它们保持不变。我假设您想在 while(t_f) 循环之前将 t_f 设置为 true。