概率算法求解圆周率π

来源:互联网 发布:java培训骗局 编辑:程序博客网 时间:2024/04/19 20:45
package com.colin;/** *  * @author Colin Yan *  */public class CalcPI {private static boolean isHit(double x, double y) {x %= 1.0;y %= 1.0;return x * x + y * y <= 1.0;}public static void main(String[] args) {int hitTimes = 0;int trialTimes = 10000000;for (int i = 0; i < trialTimes; i++) {double x = Math.random();double y = Math.random();hitTimes += isHit(x, y) ? 1 : 0;}System.out.println("PI=" + hitTimes * 4.0D / trialTimes);}}