この簡単なプログラム プログラムは、正方形へのダーツ スローをシミュレートすることにより、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
たぶん、この解決策を見つけるための他のアプローチはありますか? 助言がありますか。