임의로 생성 된 x와 y의 점이 -1과 1 사이에있을 때 제곱과 원의 비율을 찾아 몬테카를로 시뮬레이션을 복제하려고합니다. 문제가 있습니다. x 및 y에 대한 난수 생성은 모든 루프에 대해 동일한 값인 을 반환하기 때문에 발생합니다. cmd를에서동일한 숫자를 생성하는 루프의 math.random
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와 어떤 규칙이 있습니까? 또는 내 코드를 잘못 작성하고 있습니까?
'while' 루프 밖에서't_f = true; '를 다시 설정해야합니다. 감사합니다. – luk2302