Acquaintance Monte Carlo algorithm

Monte Carlo algorithm, in my opinion, is a very magical algorithm that can simulate a lot of scenes and simulated data, may be almost the same with real data, but far less than the cost of acquiring simulated real data .

Today, I use a Monte Carlo algorithm, to do two simple simulation. A π value is calculated, a further quadrature.

A, π value

How the value of π is an irrational number, not an infinite loop, around AD 480, the mathematician Zu rushed into the Northern and Southern Dynasties of the outcome of seven decimal place, today, we use a computer to simulate my simulation results .

First, to illustrate the idea of ​​simulation, as shown below, is derived by proportional relationship of the inscribed circle and a square area, as long as the area ratio is calculated Talia, we can obtain π.

Then how, without the use of π to calculate the area of ​​the inscribed circle. We can use the dot manner, a square region of n random dot, if there are x within the inner region of the inscribed circle, the area ratio is Talia n / x. If this large n, the result is very accurate.

 Specific code as follows

list_p=[]
list_p_x=[]
max_count = 100000000
first_count =10
rate = 2
count_s = 0
j=0
while first_count < max_count:
    print(first_count)
    while j < first_count:
        x = random.uniform(-1, 1)
        y = random.uniform(0, 1)
        if   x**2 + y**2 < 1:
            count_s = count_s + 1
        j = j + 1
    list_p_x.append(first_count)
    list_p.append(count_s/first_count*4)
    j=0
    count_s=0
    first_count =first_count * rate


plt.xlim(0,first_count/2)
plt.ylim (3,3.3)
plt.plot(list_p_x,list_p)
plt.hlines(y=np.pi,xmin= first_count,xmax=list_p_x, colors = "c", linestyles = "dashed")

  模拟出来的结果如下,在模拟超过1w次后,结果已经趋于稳定,基本等于3.14,这已经基本我们大部分使用场景。

 

 

二、积分

 

积分实际也可以理解是计算面试,比如下图,是y = -x^2+1 的函数图形,现在用蒙特卡罗求一下该函数的积分。

思路和求π得方法一致,也是通过随机打点的方式,根据在积分区域的散点数与矩形区域内散点数之比,乘以矩形面积,就是该积分区域面积。

分析模拟结果如下图,可以看到模拟3w到多次时,准确率很高了,与1.33不断接近,在9w次之后,基本保持重叠。

 

 

 通过蒙特卡罗模拟,生成一系列符合预期要求的随机数,就可以模拟出一个十分接近实际值得近似值,十分适应于对数值计算精度要求不是很高的场景,比如,我们在计算圆面积的是,通常都会取3.14,而不会取3.1415926.....等。

 

注:

公众号:数据志(原:跟着菜鸟一起学R语言)

原文链接:https://www.cnblogs.com/wheng/articles/11832476.html

 

Guess you like

Origin www.cnblogs.com/wheng/p/11832476.html