import random def monte_carlo_pi(n): x_1st = [random.random() for in range(n)] y_1st = [random.random() for in range(n)] coordinate=zip(x_lst,y_lst) 1s = [1 for x, y in coordinate if x ** 2 + y** 2 <= 1] pi=4*1s.count(1)/n return'{:.6f}'.format (pi) if _name__=='_main_': num =1000 print(monte_carlo_pi(1000))
时间: 2024-01-01 13:05:24 浏览: 74
这段代码存在几个语法错误,修改后的代码如下:
```
import random
def monte_carlo_pi(n):
x_lst = [random.random() for _ in range(n)]
y_lst = [random.random() for _ in range(n)]
coordinate = zip(x_lst, y_lst)
hits = [1 for x, y in coordinate if x ** 2 + y ** 2 <= 1]
pi = 4 * sum(hits) / n
return '{:.6f}'.format(pi)
if __name__ == '__main__':
num = 1000
print(monte_carlo_pi(num))
```
这段代码使用蒙特卡罗方法来计算圆周率的值。首先生成 `n` 个随机点的横纵坐标,然后统计这些点中落在单位圆内的点的个数,最后用这个个数来估算圆的面积,从而得到圆周率的值。代码中使用了 `zip` 函数来将横纵坐标打包成坐标对,使用了列表推导式来统计落在圆内的点的个数,最后用 `sum` 函数来计算这些点的个数,从而得到圆的面积。最后将面积与单位圆的面积相除,再乘以 4,就得到了圆周率的值。
相关问题
import numpy as np import matplotlib.pyplot as plt import math def count(lis): lis = np.array(lis) key = np.unique(lis) x = [] y = [] for k in key: mask = (lis == k) list_new = lis[mask] v = list_new.size x.append(k) y.append(v) return x, y mu = [14, 23, 22] sigma = [2, 3, 4] tips = ['design', 'build', 'test'] figureIndex = 0 fig = plt.figure(figureIndex, figsize=(10, 8)) color = ['r', 'g', 'b'] ax = fig.add_subplot(111) for i in range(3): x = np.linspace(mu[i] - 3*sigma[i], mu[i] + 3*sigma[i], 100) y_sig = np.exp(-(x - mu[i])**2/(2*sigma[i]**2))/(math.sqrt(2*math.pi)) ax.plot = (x, y_sig, color[i] + '-') ax.legend(loc='best', frameon=False) ax.set_xlabel('# of days') ax.set_ylabel('probability') plt.show() plt.grid(True) size = 100000 samples = [np.random.normal(mu[i], sigma[i], size) for i in range(3)] data = np.zeros(len(samples[1])) for i in range(len(samples[1])): for j in range(3): data[i] += samples[j][i] data[i] = int(data[i]) a, b = count(data) pdf = [x/size for x in b] cdf = np.zeros(len(a)) for i in range(len(a)): if i > 0: cdf[i] += cdf[i - 1] cdf = cdf/size figureIndex += 1 fig = plt.figure(figureIndex, figsize=(10, 8)) ax = fig.add_subplot(211) ax.bar(a, height=pdf, color='blue', edgecolor='white', label='MC PDF') ax.plot(a, pdf) ax.legend(loc='best', frameon=False) ax.set_xlabel('# of days for project') ax.set_ylabel('probability') ax.set_title('Monte Carlo Simulation') ax = fig.add_subplot(212) ax.plot(a, cdf) ax.legend(loc='best', frameon=False) ax.set_xlabel('# of days for project') ax.set_ylabel('probability') ax.grid(True) plt.show()修改一下代码
import numpy as np
import matplotlib.pyplot as plt
import math
def count(lis):
lis = np.array(lis)
key = np.unique(lis)
x = []
y = []
for k in key:
mask = (lis == k)
list_new = lis[mask]
v = list_new.size
x.append(k)
y.append(v)
return x, y
mu = [14, 23, 22]
sigma = [2, 3, 4]
tips = ['design', 'build', 'test']
figureIndex = 0
fig = plt.figure(figureIndex, figsize=(10, 8))
color = ['r', 'g', 'b']
ax = fig.add_subplot(111)
for i in range(3):
x = np.linspace(mu[i] - 3*sigma[i], mu[i] + 3*sigma[i], 100)
y_sig = np.exp(-(x - mu[i])**2/(2*sigma[i]**2))/(math.sqrt(2*math.pi))
ax.plot(x, y_sig, color[i] + '-', label=tips[i])
ax.legend(loc='best', frameon=False)
ax.set_xlabel('# of days')
ax.set_ylabel('probability')
plt.grid(True)
plt.show()
size = 100000
samples = [np.random.normal(mu[i], sigma[i], size) for i in range(3)]
data = np.zeros(len(samples[1]))
for i in range(len(samples[1])):
for j in range(3):
data[i] += samples[j][i]
data[i] = int(data[i])
a, b = count(data)
pdf = [x/size for x in b]
cdf = np.zeros(len(a))
for i in range(len(a)):
if i > 0:
cdf[i] += cdf[i - 1]
cdf[i] = pdf[i] + cdf[i]
figureIndex += 1
fig = plt.figure(figureIndex, figsize=(10, 8))
ax = fig.add_subplot(211)
ax.bar(a, height=pdf, color='blue', edgecolor='white', label='MC PDF')
ax.plot(a, pdf)
ax.legend(loc='best', frameon=False)
ax.set_xlabel('# of days for project')
ax.set_ylabel('probability')
ax.set_title('Monte Carlo Simulation')
ax = fig.add_subplot(212)
ax.plot(a, cdf)
ax.legend(loc='best', frameon=False)
ax.set_xlabel('# of days for project')
ax.set_ylabel('probability')
ax.grid(True)
plt.show()
python-使用蒙特卡罗(Monte Carlo)方法计算圆周率 (将抛点数设 1000000),如图 pi=3.141572
蒙特卡洛方法是一种统计模拟方法,用于解决一些难以解析的问题,通过大量随机采样来逼近精确解。为了使用这种方法估算圆周率π,我们可以假设在一个正方形内有一个单位半径的圆,然后尝试投掷大量的点到这个正方形上。根据几何知识,圆内的点数与正方形内所有点的比例接近π/4。
以下是使用Python实现的一个简单示例:
```python
import random
def estimate_pi(n):
inside_circle = 0
for _ in range(n): # 投掷n次点
x = random.uniform(0, 1)
y = random.uniform(0, 1)
if (x**2 + y**2) < 1: # 如果点在圆内
inside_circle += 1
# 圆内点的比例乘以4得到近似的π值
pi_estimate = 4 * inside_circle / n
return pi_estimate
# 抛点数设置为1000000
estimated_pi = estimate_pi(1000000)
print(f"Estimate of π with {1000000} points: {estimated_pi}")
#
阅读全文