求解圆周率可以采用蒙特卡罗方法,在一个正方形中撒点,根据在 1/4 圆内点的数量占总撒点数的比例计算圆周率值。
![img](https://img-blog.csdnimg.cn/img_convert/2299b04b854180d4fc71ee932fa18233.png)
请以 123
作为随机数种子,获得用户输入的撒点数量,编写程序输出圆周率的值,保留小数点后 6 位。
样例
输入(1)
1024
输出(1)
3.218750
代码
from random import random, seed
DARTS = eval(input())
seed(123)
hits = 0.0
for i in range(DARTS):
x, y = random(), random()
dist = pow(x ** 2 + y ** 2, 0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits/DARTS)
print("{:.6f}".format(pi))
这是本课程的实例4,请注意:from...import 引入具体的函数,使用seed()需要提前引入