蒙特卡罗模拟求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);
  }
}
posted @ 2022-05-20 11:19  Scenery_Shelley  阅读(35)  评论(0)    收藏  举报