java實現蒙特卡洛方法求圓周率


前言

蒙特·卡羅方法(Monte Carlo method),也稱統計模擬方法,是二十世紀四十年代中期由於科學技術的發展和電子計算機的發明,而被提出的一種以概率統計理論為指導的一類非常重要的數值計算方法。是指使用隨機數(或更常見的偽隨機數)來解決很多計算問題的方法。
今天我們使用蒙特卡洛方法來求圓周率的值。

實現


圓的面積    =   PI*R*R
正方形面積  =   (2*R)*(2*R) = 4*R*R
PI         =   4*圓面積/正方形面積

代碼實現

public class Client {

  private static double monteCarlo(int n) {
    int insidePoints = 0;//在圓中的點個數
    int totalPoints = n;//在正方形中點個數
    int R = 100;//圓半徑
    for (int i = 0; i < n; i++) {
      int x = (int) (Math.random() * (2 * R));
      int y = (int) (Math.random() * (2 * R));
      if (contain(x, y, R)) {
        insidePoints++;
      }
    }
    return 4 * 1.0 * insidePoints / totalPoints;
  }

  private static boolean contain(int x, int y, int R) {
    return Math.pow(x - R, 2) + Math.pow(y - R, 2) <= R * R;
  }

  public static void main(String[] args) {
    System.out.println("PI = " + monteCarlo(10000));
    System.out.println("PI = " + monteCarlo(100000));
    System.out.println("PI = " + monteCarlo(1000000));
    System.out.println("PI = " + monteCarlo(10000000));
  }
}

輸出結果為

PI = 3.1668
PI = 3.12992
PI = 3.139812
PI = 3.140758

點數越多,PI值越精確。

參考

蒙特卡洛方法求圓周率與定積分及python實現。-知乎
java 蒙特卡洛_java算法3_蒙特卡洛方法(Monte Carlo method)求PI和橢圓面積。-CSDN


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM