为了估计PI的数量,我想特别使用蒙特卡罗方法应用于1x1平方内半径为1的圆形飞镖游戏。可以找到更多描述here。我想要一个Java代码来估计最多200位的PI。我使用了BigDecimal
,但它显示了49个十进制数字,其余的数字为零。我感谢任何帮助。
import java.util.*;
import java.math.BigDecimal;
public class PiFinder {
// description
public static void main(String[] args) {
Scanner iteration = new Scanner(System.in);
System.out.print("Enter the number of iteration: ");
int NoThrows = iteration.nextInt();
BigDecimal PI = new BigDecimal(PIcalculation(NoThrows));
PI = PI.setScale(200);
// Difference of our estimated PI and the actual PI
BigDecimal Difference = new BigDecimal(0);
BigDecimal actualPI = new BigDecimal(Math.PI);
System.out.println("Actual PI: " + actualPI);
Difference = PI.subtract(actualPI);
// Display results
System.out.println("The Number of Throws = " + NoThrows);
System.out.println("***************************");
System.out.println("Estimated PI = " + PI);
System.out.println("Difference = " + Difference);
}
// Deteremine a thrown dart is inside the circle
public static boolean insideCircle(double pos_X, double pos_Y) {
double distance = Math.sqrt((pos_X * pos_X) + (pos_Y * pos_Y));
return (distance < 1.0);
}
public static double PIcalculation(int NoThrows) {
Random randomGen = new Random(System.currentTimeMillis());
int hits = 0;
double PI = 0;
for (int i = 1; i <= NoThrows; i++) {
double pos_X = (randomGen.nextDouble()) * 2 - 1.0;
double pos_Y = (randomGen.nextDouble()) * 2 - 1.0;
if (insideCircle(pos_X, pos_Y)) {
hits++;
}
}
double dthrows = NoThrows;
// the formule
PI = (4.0 * (hits / dthrows));
return PI;
}
}
答案 0 :(得分:3)
你的PiCalculation会返回一个双精度数,你不能期望它具有更高的精确度。
如果你想更进一步,请到处使用BigDecimal。
但无论如何使用这种方法,即使投掷10 ^ 10,你也只有10位小数。
你的双倍的49位小数是由于双重缺乏精确度