首页 > 解决方案 > 使用蒙特卡罗方法的 pi 值输出错误

问题描述

我尝试使用蒙特卡洛方法(不使用任何可视化)制作一个 JAVA 程序来计算 pi 的值,对我来说一切似乎都很好,但每当我运行它时,答案总是 0.0 。无法弄清楚,有什么问题请帮忙。

这是代码:

    import java.util.*;

    // Compiler version JDK 11.0.2

    class PiMonteCarlo{
        public static void main(String args[]){ 
            Random rand =new Random();
            double r=1.0;
            int cir=0,sq=0,range=200+1,min=0;
            for(int i=1;i<=200000;i++){
                double y = rand.nextDouble();
                double x = rand.nextDouble();
                double d=(x*x)+(y*y);
                if(d<=r){
                    cir++;
                }
            sq++;
            }
            double rat=cir/sq;
            System.out.print(4*rat);
        }
    }

标签: javapi

解决方案


cir / sq 是整数除法。尝试:

double rat = (double)cir / sq;

推荐阅读