java - 使用蒙特卡罗方法的 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);
}
}
解决方案
cir / sq 是整数除法。尝试:
double rat = (double)cir / sq;
推荐阅读
- nginx - 如何使用一个 ssl 设置 nginx 多个应用程序和多个端口
- python - 实现 Selenium 以使用更改的身份验证代理
- ios - 基于设备方向的 Deep ArView 更新帧输出
- python - 如何在 Python Pandas 中从 DataFrame 绘制简单图?
- angular - 有人可以解释我们如何在角度中使用 @ViewChild() 装饰器动态传递模板引用吗
- mongodb - 在 mongoDB 中查询以找到最大错误的用户
- reactjs - 如何从只有 customerId 的条带中检索客户的卡详细信息
- node.js - 在 jwt 符号内使用 ENV 变量
- python - 如何在 Keras 中使用预训练的 CNN 实现连体网络?
- python - 如何使用python杀死外部进程?