1

この簡単なプログラム プログラムは、正方形へのダーツ スローをシミュレートすることにより、pi の推定値を計算します。

条件:ランダムな浮動小数点数を生成し、-1 から 1 の間になるように変換します
。x に格納します。y について繰り返します。(x, y) が単位円内にあること、つまり、(0, 0) と (x, y) の間の距離が <= 1 であることを確認します。

ratio hits / triesこの後、比率とほぼ同じであるを見つける必要がありますcircle area / square area = pi / 4。(正方形は 1 対 1)。

コード:

public class MonteCarlo {
    public static void main(String[] args) 
    {
        System.out.println("Number of tries");
        Random generator = new Random(42);
        Scanner in = new Scanner(System.in);
        int tries = in.nextInt();

        int hits = 0;
        double x, y;
        for (int i = 1; i <= tries; i++)
        {
            // Generate two random numbers between -1 and 1            
            int plusOrMinus = generator.nextInt(1000);
            if (plusOrMinus > 500) x = generator.nextDouble();                
            else x = -generator.nextDouble();

            plusOrMinus = generator.nextInt(10000);
            if (plusOrMinus > 5000) y = generator.nextDouble(); 
            else y = -generator.nextDouble();             

            if (Math.sqrt((x * x) + (y * y)) <= 1) // Check whether the point lies in the unit circle
            {
                hits++;
            }
        }

        double piEstimate = 4.0 * hits / tries;
        System.out.println("Estimate for pi: " + piEstimate);
    }
}

テスト出力:

  Actual output            Expected output
  -----------------------------------------------
  Number of tries          Number of tries
  1000                     1000
- Estimate for pi: 3.176   Estimate for pi: 3.312

  Actual output               Expected output
  -----------------------------------------------------
  Number of tries             Number of tries
  1000000                     1000000
- Estimate for pi: 3.141912   Estimate for pi: 3.143472

たぶん、この解決策を見つけるための他のアプローチはありますか? 助言がありますか。

4

2 に答える 2

6

-1 と 1 の間のランダムな double を生成するには、次を試してください。

generator.nextDouble() * 2 - 1

ところで:静的シードでランダムを初期化し続けると、常に同じ結果が得られます。それ以外の場合、結果が十分でないことが懸念される場合は、モンテカルロが近似値にすぎないことに注意してください。結局のところ、乱数に基づいているため、結果サンプル ソリューションとは異なります ;-)

于 2013-07-03T08:57:33.303 に答える