2017-03-21 6 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;を設定するとすぐに、whileループを再度入力することはないので、常に同じ半径を印刷します。したがって、radiuscountを印刷した後、コードをt_f = true;に変更する必要があります。

t_fを完全に削除し、代わりにbreak;を使用してください。

0

t_fをfalseに設定し、i = 0の反復のみが実際に何かを行います。他のすべての反復では、半径とカウントが印刷されます。これは変更されません。 while(t_f)ループの前にt_fをtrueに設定したかったと思います。

+0

ありがとう!私は何か変わったことを知っていた.. –

関連する問題