1 Star 0 Fork 51

fosterkong/Book5_Essentials-of-Probability-and-Statistics

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Bk5_Ch15_05.py 1.10 KB
一键复制 编辑 原始数据 按行查看 历史
Visualize-ML 提交于 2022-12-08 07:35 +08:00 . Add files via upload
###############
# Authored by Weisheng Jiang
# Book 5 | From Basic Arithmetic to Machine Learning
# Published and copyrighted by Tsinghua University Press
# Beijing, China, 2022
###############
import numpy as np
import matplotlib.pyplot as plt
l = 1
# length of needles
t = 2
# distance between parallel lines
num = 2000
theta_1 = 0
theta_2 = np.pi/2
def f(theta):
return np.sin(theta)/2
theta_array = np.arange(theta_1, theta_2, np.pi/100)
x_array = f(theta_array)
x_max = t/2
theta_rand = theta_1 + (theta_2 - theta_1)*np.random.random(num)
x_rand = np.random.random(num)*x_max
ind_below = np.where(x_rand < f(theta_rand))
ind_above = np.where(x_rand >= f(theta_rand))
fig, ax = plt.subplots()
plt.scatter(theta_rand[ind_below], x_rand[ind_below],
color = "b", marker = '.')
plt.scatter(theta_rand[ind_above], x_rand[ind_above],
color = "r", marker = 'x')
plt.plot(theta_array, x_array, color = "k")
plt.tight_layout()
plt.xlabel('$\u03B8$')
plt.ylabel('$x$')
estimated_pi = num/np.sum(x_rand < f(theta_rand))*2*l/t
print(estimated_pi)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/fosterkong/Book5_Essentials-of-Probability-and-Statistics.git
git@gitee.com:fosterkong/Book5_Essentials-of-Probability-and-Statistics.git
fosterkong
Book5_Essentials-of-Probability-and-Statistics
Book5_Essentials-of-Probability-and-Statistics
main

搜索帮助