1
我必须使用蒙特卡洛方法来计算pi。需要得到(-1,1)之间的xy坐标。然而,每次运行程序时,它都会给出0的答案。我不确定我做错了什么,任何人都可以帮忙吗?使用蒙特卡洛方法计算pi java - 计算不起作用
package montecarlo;
import java.util.Scanner;
import java.io.PrintStream;
import java.util.Random;
public class MonteCarlo {
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter total number of dart throws");
int nThrows = keyboard.nextInt();
double PI= calculatePi(nThrows);
PrintStream ps = new PrintStream("PiEstimate.txt");
ps.printf("PI estimate = %.4f", PI);
}
public static boolean insideCircle (double x, double y)
{
double range = Math.sqrt((x * x) + (y * y));
return (range < 1.0);
}
public static double calculatePi(int nThrows)
{
int dartsInCircle = 0;
double piEstimate;
Random rGenerator = new Random();
for (int i=0; i < nThrows; i++) {
double x = rGenerator.nextDouble()*Math.pow(-1, rGenerator.nextInt());
double y = rGenerator.nextDouble()*Math.pow(-1, rGenerator.nextInt());
if (insideCircle(x,y))
dartsInCircle++;
} piEstimate=(4.0*(dartsInCircle/nThrows));
return piEstimate;
}
}
谢谢你的帮助! –