编写一个小程序计算圆周率π的值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了编写一个小程序计算圆周率π的值相关的知识,希望对你有一定的参考价值。


/**
 * 假设这个圆的半径是1。那么圆的面积就是π而外接正方形的面积是4.
 * 随便产生正方形中的一个点。
 * 该点落在这个圆内的概率是  
 * 圆面积/正方形面积 = π/4
 *
 */
public class GetValueπ {

    public static void main(String[] args) {
        final int Number_Of_Trials = 10000000;
        int numberOfHits = 0;
        
        for(int i = 0;i < Number_Of_Trials;i++){
            double x = Math.random() * 2.0 - 1;
            double  y = Math.random() * 2.0 - 1;
            if(x*x + y*y <= 1){
                numberOfHits++;
            }
            
            double pi = 4.0 * numberOfHits / Number_Of_Trials;
            System.out.println("PI is " + pi);
        }
    }
}

 

 

 

以上是关于编写一个小程序计算圆周率π的值的主要内容,如果未能解决你的问题,请参考以下文章