这个简单的程序程序通过模拟飞镖投掷到正方形上来计算 pi 的估计值。
Сonditions:生成一个随机浮点数并将其转换为介于 -1 和 1 之间。
存储在 x 中。对 y 重复。检查 (x, y) 在单位圆内,即 (0, 0) 和 (x, y) 之间的距离 <= 1。
在此之后,需要找到ratio hits / tries
与比率大致相同的circle area / square area = pi / 4
。(正方形是每 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
也许,是否存在其他方法来找到这个解决方案?有什么建议么。