蒙特卡洛演算法簡單理解與demo
阿新 • • 發佈:2018-11-29
本文轉自:https://blog.csdn.net/u011021773/article/details/78301557
蒙特卡洛演算法,實際上就是用頻率估計概率。
首先我們知道一個邊長為2的正方形面積是22=4,他的內接圓的面積是π1,那麼我們在這樣一個正方形內隨機生成10000個點,落在圓裡的點的個數/10000就應該是π/4,所以我們可以估計出π是落在圓裡的點的個數*4/10000.
直接看程式碼:
import numpy as np
radius=1
test_num=100000
#random generate 10000 points in a sqare width is 2,and the center is in origin
sqare_x=2*np.random.random_sample(test_num)-1
sqare_y=2*np.random.random_sample(test_num)-1
incircle_point_num=0
#count how many points in the incircle
for point_count in range(len(sqare_x)):
if(sqare_x[point_count]*sqare_x[point_count]+
sqare_y[point_count]*sqare_y[point_count]<
radius*radius):#judge if the distance lower than radius
incircle_point_num+=1
print 'PI: '+str(4.0*incircle_point_num/test_num)
這裡隨機生成了10000個在邊長為2,中心在原點的正方形中的點,根據座標判斷是否在內接圓內,統計內接圓內點的個數,最後根據公式求出π。
準確度基本上隨著樣本個數增加而增加,下面是測試的一組統計:
再測下去計算太慢,也沒有意義了,畢竟我不是真的想知道π是多少。
根據統計結果可以看出來,測試樣本越大,精確度也就越高,頻率也就越接近概率值。
所以這套蒙特卡洛方法可以用來求出積分,也是使用積分割槽域的面積和外接長方形的面積比的方式估算。
例如:
import numpy as np
import math
#calculate the function
def f(x):
return math.exp(-1*x*x/2)/math.sqrt(2*math.pi)
test_num=10000
maxy=1/math.exp(0.5)/math.sqrt(2*math.pi)#calculate the top bound
rectangle_y=np.random.random_sample(test_num)*(1/math.sqrt(2)-maxy)
rectangle_x=np.random.random_sample(test_num)
inarea_point_num=0
#count how many points in the area
for point_count in range(len(rectangle_x)):
if(rectangle_y[point_count]<f(rectangle_x[point_count])):
inarea_point_num+=1
print 'area: '+str(1.0*inarea_point_num/test_num*(1/math.sqrt(2)-maxy) )
求出來的結果是0.340433079875,與準確值相差無幾
更多案例請關注“思享會Club”公眾號或者關注思享會部落格:http://gkhelp.cn/