2017-03-21 12 views
0

임의로 생성 된 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); 
     } 
    } 
} 

결과 :

result from cmd

루프 내부 인 Math.random와 어떤 규칙이 있습니까? 또는 내 코드를 잘못 작성하고 있습니까?

+3

'while' 루프 밖에서't_f = true; '를 다시 설정해야합니다. 감사합니다. – luk2302

답변

1

나는 Math.random()이 올바르게 작동하지 않는다고 생각합니다. 귀하의 루프 논리는 단순히 꺼져 있습니다. 루프를 다시 입력하지 않으므로 t_f = false;을 설정하면 동일한 반지름을 항상 인쇄합니다. 따라서 radiuscount을 인쇄 한 후 코드를 t_f = true;으로 변경해야합니다.

단순히 t_f을 완전히 삭제하고 대신 break;을 사용하십시오.

0

t_f를 false로 설정하고 i = 0 인 반복 만 실제로 수행합니다. 다른 모든 반복은 반지름과 개수를 인쇄하며 변경되지 않습니다. while (t_f) 루프 전에 t_f를 true로 설정하려고한다고 가정합니다.

+0

! 나는 이상한 일을하고 있다는 것을 알았다. .. –