2017-10-16 90 views
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; 

} 
} 

回答

1

你将一个intint这里:(dartsInCircle/nThrows)

由于dartsInCircle将始终小于nThrows,整数除法将始终返回0。您需要将其中一个操作数加倍。

编辑:如果您使用了足够好的IDE(如IntelliJ),它应该会提示您出现“精度丢失”警告或类似错误。

+0

谢谢你的帮助! –