首頁 > Java > java教程 > Java使用Math.random()結合蒙特卡羅方法計算pi值方法介紹

Java使用Math.random()結合蒙特卡羅方法計算pi值方法介紹

巴扎黑
發布: 2017-09-19 11:38:03
原創
1862 人瀏覽過

這篇文章主要介紹了Java使用Math.random()結合蒙特卡羅方法計算pi值的方法,簡單說明了結合具體實例蒙特卡洛方法的原理,並結合具體實例形式分析了java使用蒙特卡洛方法計算PI值的操作技巧,需要的朋友可以參考下

本文實例講述了Java使用Math.random()結合蒙特卡羅方法計算pi值。分享給大家供大家參考,具體如下:

一、概述​​

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

詳細可參考百度百科:https://baike.baidu.com/item/%E8%92%99%E7%89%B9%C2%B7%E5%8D%A1%E7%BD %97%E6%96%B9%E6%B3%95

#二、實作程式碼


##

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

/**

 * Monte Carlo algorithm

 */

import java.math.*;

public class PI {

  /**

   * @param args

   */

  public static void main(String[] args) {

    // TODO Auto-generated method stub

    double xf = 0.0d;

    double yf = 0.0d;

    int total = 0;

    for(int i = 0;i<1000000;i++){

      xf = Math.random();

      yf = Math.random();

      if(Math.sqrt(xf*xf+yf*yf) < 1)

        total++;

    }

    System.out.println("脚本之家测试结果:");

    System.out.println(4*(total/1000000.0));

  }

}

登入後複製

運行結果:

以上是Java使用Math.random()結合蒙特卡羅方法計算pi值方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板