蒙特卡罗法(随机模拟法)

目录

1、概述

2、代码

(1)求圆周率

(2)用随机透点法计算0--1上sin(x)的积分

(3)图像



1、概述

     随机模拟方法也称为Monte Caro(孟特卡罗)方法,是一种基于“随机数”的计算方法。这一方法源于美国在第二次世界大战中研制原子弹的“曼哈顿计划”。该计划的主持人之一,数学家,冯-诺依曼用驰名世界的赌城—摩纳哥的Monte Caro来命名这种方法,为他蒙上神秘的面纱。(蒙特卡法)

2、代码

(1)求圆周率

这个代码比较简单,但是要等好久好久,等得让你怀疑人生,哈哈哈.....

from random import random
import numpy as np
n=2**31
hist=0
for i in range(1,n):
    x,y=random(),random()
    dist=np.sqrt(x**2+y**2)
    if dist<=1.0:
        hist=hist+1
pi=4*(hist/n)
print(pi)
#结果(太难等了,我取n=100000)

3.14608

Process finished with exit code 0

(2)用随机透点法计算0--1上sin(x)的积分

import numpy as np
import matplotlib.pyplot as plt
from pylab import *
import matplotlib; matplotlib.use('TkAgg')
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False


n=100000
x_min,x_max=0.0,1.0
y_min,y_max=0.0,1.0
x=np.random.uniform(x_min,x_max,n)
y=np.random.uniform(y_min,y_max,n)

def f(x):
    return np.sin(x)
n1=np.sum(np.where(y

(3)图像

蒙特卡罗法(随机模拟法)_第1张图片

你可能感兴趣的:(#,数值分析,算法,python,机器学习)