Python圆周率问题

来源:Python语言程序设计 -嵩天

一、问题描述

计算圆周率pi的值。

二、解决思路

如下图所示,向含有半径为1的1/4圆的11的正方形中撒1000010000个点,计算落入圆中的点数与正方形内的点数的比值。比值即为1/4圆的面积,也为1/4pi的值。
在这里插入图片描述

三、代码

'''
如笔记中所示图:
向含有半径为1的1/4圆的1*1的正方形中撒1000*1000个点,计算落入圆中的点数与正方形内的点数的比值。
比值即为1/4圆的面积,也为1/4pi的值。
'''

from random import random
from time import perf_counter

squar = 10000*10000
point = 0.0
start = perf_counter()
for i in range(1, squar+1):
    x,y = random(),random()
    s = x**2+y**2
    if s <= 1:
        point = point+1 
pi = 4*(point/squar)
print("圆周率的值:{}".format(pi))
end = perf_counter()
print("运行时间:{:.5f}".format(end - start))

运行结果:

runfile('E:/Python/MOCC_bit/Calpi.py', wdir='E:/Python/MOCC_bit')
圆周率的值:3.141696
运行时间:98.29037

猜你喜欢

转载自blog.csdn.net/shine_00/article/details/119644038