”Pi Day is celebrated on March 14th (3/14) around the world. Pi (Greek letter “π”) is the symbol used in mathematics to represent a constant — the ratio of the circumference of a circle to its diameter — which is approximately 3.14159. Pi Day is an annual opportunity for math enthusiasts to recite the infinite digits of Pi, talk to their friends about math, and to eat pie. “ https://www.piday.org/
图片来源 https://www.piday.org/
圆周率π有很多的计算方法,比如圆的周长与直径的比值,也等于圆形之面积与直径平方之比,……
根据不同的计算方法可以写出很多有意思的程序来,记得阿信在早些年学习Python的时候就遇到这样的题目,虽然现在这些东西早已成了大路货,不过回忆起来还是很有意思。采用蒙特卡洛方法,依据是π等于圆形之面积与直径平方之比。具体的实现方式是通过生成随机数,将落在圆内的随机点数量除以总的随机点数量得到π值,计算精度与总的随机点生成次数有关。为了减少计算量,可取圆的1/4,进行随机点的投放。
代码如下,很简单。
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 13 12:59:32 2021
@author: A Xin
@email:axin_cae@163.com
"""
from random import random
num_in_circle = 0.0
total_num = 1000000
for i in range(total_num):
x, y = random(), random()
dist = pow(x**2.0 + y**2.0, 0.5)
if dist <= 1.0:
num_in_circle += 1
pi_value = 4.0*(num_in_circle / total_num)
print pi_value
阿信
3.13 ------>>> 3.14