Loading... The minute you think of giving up, think of the reason why you held on so long. ## 来源 该方法的名字来源于世界著名的赌城蒙特卡罗。博彩和概率,二者相视一笑、不谋而合。这种方法最初应用于20世纪40年代美国的曼哈顿原子弹计划,如今在数据分析和机器学习领域中到处都有他的身影。 ## 原理 抽取大量的随机样本然后逼近事件的真实概率 ## 蒙塔卡洛方法计算pi ```python #使用蒙特卡洛方法计算pi #random库(梅森旋转法) import random #圆内点的数量 inside = 0; #总点数(可变) total = 1000000 #迭代总点数 for i in range(total): #生成随机的x,y坐标 x = random.uniform(-1, 1) y = random.uniform(-1, 1) #检查点数是否在圆内 if x**2 + y**2 <=1: inside += 1 #使用蒙特卡洛方法计算pi pi = 4 * inside / total #打印计算出的pi值 print(pi) ``` 方法二 ```python import random total = [10, 100, 1000, 10000, 100000, 1000000, 5000000] #随机点数 for t in total: in_count = 0 for i in range(t): x = random.random() y = random.random() dis = (x**2 + y**2)**0.5 if dis<=1: in_count += 1 print(t,'个随机点时,π是:', 4*in_count/t) ``` [如何通俗地理解「蒙特卡洛方法」,它解决问题的基本思路是什么,目前主要应用于哪些领域? - 知乎 (zhihu.com)](https://www.zhihu.com/question/441076840) [蒙特卡罗方法详解 - 知乎 (zhihu.com)](https://zhuanlan.zhihu.com/p/369099011) 最后修改:2023 年 06 月 05 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 3 如果觉得我的文章对你有用,请随意赞赏