利用概率的方法求圆周率

利用概率的方法求圆周率

public class Test12 {
    public static void main(String[] args) {
        Square[] arr = new Square[1000000];
        double x;
        double y;
        boolean flag;
        double count = 0;
        double sum;
        for(int i = 0;i < 1000000;i ++){
            x = Math.random() * 2;
            y = Math.random() * 2;
            Square s = new Square(x,y);
            arr[i] = s;
        }
        for (int j = 0;j < 1000000;j ++){
            flag = Cal(arr[j].x,arr[j].y);
            if(flag){
                count++;
            }
        }
        sum=count/1000000;
        System.out.println(sum);
        System.out.println(Math.PI/4);
    }
    public static boolean Cal(double x,double y){
        double z = (x-1)*(x-1) + (y-1)*(y-1);
        System.out.println(z);
        return Math.sqrt(z) < 1;
    }
}

class Square{
    double x;
    double y;
    Square(double x,double y){
        this.x = x;
        this.y = y;
    }
}

 

 
posted @ 2021-09-21 19:11  我的世界开始下雪  阅读(121)  评论(0编辑  收藏  举报