布丰实验
数学原理
python代码
import random as rd
import numpy as np
import math
import matplotlib. pyplot as plt
import matplotlib
matplotlib. rcParams[ 'font.family' ] = 'SimHei'
matplotlib. rcParams[ 'axes.unicode_minus' ] = False
% matplotlib inline
a= 1
l= 0.5
n= 100000
k= 100
m= 0
x_history= [ ]
phi_history= [ ]
joint_list= [ ]
for i in range ( n) :
x= rd. uniform( 0 , a/ 2 )
phi= rd. uniform( 0 , math. pi)
x_history. append( x)
phi_history. append( phi)
if l* math. sin( phi) / 2 >= x:
m+= 1
joint_list. append( 1 )
else :
joint_list. append( 0 )
PI= 2 * l* n/ ( a* m)
print ( f'模拟所得圆周率: { PI} ' )
plt. scatter( phi_history, x_history, c= joint_list, cmap= 'bwr' , alpha= 0.5 )
plt. colorbar( label= '是否相交' )
plt. xlabel( '针中点与最近平行线距离' )
plt. ylabel( '针角度' )
plt. title( '布丰模拟实验分布图' )
plt. xticks( [ 0 , math. pi)
plt. yticks( [ 0 , a/ 2 ] )
plt. show( )