起源
[1946: John von Neumann, Stan Ulam, and Nick Metropolis, all at the Los Alamos Scientific Laboratory, cook up the Metropolis algorithm, also known as the Monte Carlo method.]1946年,美國拉斯阿莫斯國家實驗室的三位科學家John von Neumann,Stan Ulam 和 Nick Metropolis共同發明,被稱為蒙特卡洛方法。它的具體定義是:在廣場上畫一個邊長一米的正方形,在正方形內部隨意用粉筆畫一個不規則的形狀,現在要計算這個不規則圖形的面積,怎么計算列?蒙特卡洛(Monte Carlo)方法告訴我們,均勻的向該正方形內撒N(N 是一個很大的自然數)個黃豆,隨后數數有多少個黃豆在這個不規則幾何形狀內部,比如說有M個,那么,這個奇怪形狀的面積便近似于M/N,N越大,算出來的值便越精確。在這里我們要假定豆子都在一個平面上,相互之間沒有重疊。(撒黃豆只是一個比喻。)
特點
蒙特卡洛方法的偉大之處,在于對精確性問題無法解決的時候,利用“模擬”的思想來求解。 在各個領域得以應用。本質是模擬(simulation): 利用大量隨機輸入,產生各種輸出;結果的概率分布就是真實分布的“近似”。所以,輸入的分布是否隨機(目前計算機所能做的就是偽隨機,并不能產生真正的隨機分布),這個過程我們成為Sampling Random Variables。
計算圓周率近似值代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package com.xu.main; import java.util.Scanner; public class P9_1 { static double MontePI( int n) { double PI; double x, y; int i, sum; sum = 0 ; for (i = 1 ; i < n; i++) { x = Math.random(); y = Math.random(); if ((x * x + y * y) <= 1 ) { sum++; } } PI = 4.0 * sum / n; return PI; } public static void main(String[] args) { int n; double PI; System.out.println( "蒙特卡洛概率算法計算圓周率:" ); Scanner input = new Scanner(System.in); System.out.println( "輸入點的數量:" ); n = input.nextInt(); PI = MontePI(n); System.out.println( "PI=" +PI); } } |
輸出:
1
2
3
4
|
蒙特卡洛概率算法計算圓周率: 輸入點的數量: 9999999 PI= 3.1417975141797516 |
總結
以上就是本文關于蒙特卡洛算法起源及特點的簡介,還有如何利用這種算法思路在Java編程中求圓周率的近似值實例,希望對大家有所幫助。喜歡的朋友請繼續關注服務器之家!
原文鏈接:http://blog.csdn.net/xuxian361/article/details/8130948