用python计算投1000,10000次骰子点数3朝上的概率,并画图(横坐标为投的次数,纵坐标为频率)
时间: 2024-09-25 08:08:07 浏览: 49
在Python中,我们可以使用`random`模块来模拟投掷骰子的过程,同时利用统计学原理计算点数为3的概率。然后通过`matplotlib`库来绘制结果的频率分布图。这里是一个简单的示例:
```python
import random
import matplotlib.pyplot as plt
# 定义投掷骰子的函数
def roll_dice():
return random.randint(1, 6)
# 投掷骰子的次数
n_trials = 10000
# 初始化计数器
count_3 = 0
for _ in range(n_trials):
if roll_dice() == 3:
count_3 += 1
# 计算3朝上概率
probability_3 = count_3 / n_trials
# 绘制频率分布图
x_axis = [i for i in range(1, n_trials+1)]
y_axis = [count_3 * (1/n_trials) for _ in x_axis] # 每次试验频率等于概率
plt.plot(x_axis, y_axis, 'o-', label='Probability of rolling a 3')
plt.xlabel('Number of trials')
plt.ylabel('Frequency')
plt.title(f"Probability of Rolling a 3 ({probability_3*100:.2f}%)")
plt.legend()
plt.show()
# 输出概率
print(f"Probability of getting a 3 after {n_trials} trials is {probability_3 * 100:.2f}%")
阅读全文