"景先生毕设|www.jxszl.com

蒙特卡罗法计算π的值[python编程练习]

2023-09-12 15:40编辑: www.jxszl.com景先生毕设
蒙特卡罗法计算π的值[python编程练习]
题目:用蒙特卡罗法计算π的值通过计算落在单位圆内的点与落在正方形内的 点的比值求PI。
代码示例:


from random import random
from math import sqrt
 
max = 2000000
count = 0
for i in range (1,max):
    x, y = random(),random()
    dist = sqrt(x**2+y**2)
    if dist <= 1:
        count = count + 1
pi = 4*(count/max)
print("π的值为%f"%pi)


原文链接:http://www.jxszl.com/biancheng/python/446348.html