蒲丰投针求圆周率python可视化
时间: 2023-11-17 22:03:14 浏览: 150
蒲丰投针是一种用来估算圆周率的方法,其基本思想是将一根长度为L的针随机投掷到一个由等距平行线构成的纸面上,然后统计针与平行线相交的次数,通过这个次数与投针总数的比值来估算圆周率。下面是一个Python可视化的实现:
<<引用>>
```python
import random
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def calpai():
po = []
n = 1000
r = 1.0
a, b = (0.0, 0.0)
x_neg, x_pos = a - r, a + r
y_neg, y_pos = b - r, b + r
count = 0
xpoints = np.array(0)
ypoints = np.array(0)
xxpoints = np.array(0)
yypoints = np.array(0)
for i in range(0, n):
x = random.uniform(x_neg, x_pos)
y = random.uniform(y_neg, y_pos)
if x*x + y*y <= 1.0:
count += 1
xpoints = np.append(xpoints, [x])
ypoints = np.append(ypoints, [y])
plt.plot(xpoints, ypoints,"o")
else:
xxpoints = np.append(xxpoints, [x])
yypoints = np.append(yypoints, [y])
plt.plot(xxpoints, yypoints,"o")
xx = 0
yy = 0
r = 1
a_x = np.arange(0, 2 * np.pi, 0.01)
a = xx + r * np.cos(a_x)
b = yy + r * np.sin(a_x)
plt.plot(a, b, color='deeppink', linestyle='--')
plt.plot(a, -b, color='deeppink', linestyle='--')
plt.axis('equal')
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.show()
print ((count / float(n)) * 4)
calpai()
```
运行上述代码,即可得到一个可视化的蒲丰投针求圆周率的结果。其中,红色的虚线表示圆的边界,蓝色的点表示针的投掷位置,而绿色的点则表示针与平行线相交的位置。程序最后输出的结果即为估算出的圆周率。
阅读全文