使用Java Math.random()利用蒙特卡洛方法计算pi值

来源:互联网 发布:淘宝3ds知乎 编辑:程序博客网 时间:2024/06/12 00:50
/** * Monte Carlo algorithm */import java.math.*;public class PI {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        double xf = 0.0d;        double yf = 0.0d;        int total = 0;        for(int i = 0;i<1000000;i++){            xf = Math.random();            yf = Math.random();            if(Math.sqrt(xf*xf+yf*yf) < 1)                total++;        }        System.out.println(4*(total/1000000.0));    }}
0 0
原创粉丝点击