生成离散随机变量

Python 中的蒙特卡洛模拟

Izzy Weber

Curriculum Manager, DataCamp

必需的导入

import scipy.stats as st

import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt
Python 中的蒙特卡洛模拟

离散均匀分布

理论概率质量函数(PMF): 离散均匀分布的理论概率质量函数

Python 中的蒙特卡洛模拟

从离散均匀分布采样

low = 3 
high = 21
samples = st.randint.rvs(low, high, size=1000)
samples_dict = {"nums":samples}
sns.histplot(x="nums", data=samples_dict, bins=6, binwidth=0.3)

离散均匀分布样本结果图

Python 中的蒙特卡洛模拟

几何分布

给定成功概率 p,得到一次成功所需试验次数 X 的分布。

概率质量函数,p = 0.5 p = 0.5 时几何分布的理论概率质量函数

Python 中的蒙特卡洛模拟

几何分布

概率质量函数,p = 0.3 p = 0.3 时几何分布的理论概率质量函数

Python 中的蒙特卡洛模拟

从几何分布采样

p = 0.2
samples = st.geom.rvs(p, size=1000)
samples_dict = {"nums":samples}
sns.histplot(x="nums", data=samples_dict)

几何分布样本结果图

Python 中的蒙特卡洛模拟

更多离散概率分布

  • 泊松分布(scipy.stats.poisson
    • 表示在给定时间或空间区间内发生给定事件数的概率
  • 二项分布(scipy.stats.binom
    • 表示在 n 次相互独立试验中成功次数的概率
  • 还有更多!
1 https://docs.scipy.org/doc/scipy/reference/stats.html#discrete-distributions
Python 中的蒙特卡洛模拟

让我们练习!

Python 中的蒙特卡洛模拟

Preparing Video For Download...