蒙特卡罗模拟求PI
假设圆的半径为1,圆的面积为PI,外接正方形的面积为4.
随机产生一个点落在圆内的概率为PI/4
import java.util.*;
class Main {
public static void main(String[] args){
final int NUMBER_OF_TRIALS = 10_000_000;
int numberOfHits = 0;
for(int i = 0; i < NUMBER_OF_TRIALS; i++){
double x = Math.random() * 2 -1;
double y = Math.random() * 2 -1;
if(x * x + y * y <= 1){
numberOfHits++;
}
}
double pi = 4.0 * numberOfHits / NUMBER_OF_TRIALS;
System.out.println("PI is " + pi);
}
}

浙公网安备 33010602011771号