python - 如何使用库函数 scipy.stats.binom.pmf 返回给定概率的二项分布中的试验次数 (n)?

标签 python python-3.x scipy statistics binomial-theorem

是否可以让scipy.stats.binom.pmf(x, n, p)返回试验次数(n),概率为,数字成功次数 (x) 和成功概率 (p) 已知吗?

示例问题:

Alex 需要 throw 多少次才能有 90% 的把握至少击中目标 10 次?

地点:

  • 概率 = 0.90
  • p = 0.50
  • x = 10

最佳答案

你可以做这样的事情。您想要计算的是 scipy.stats 所谓的生存函数 (sf),即 1-cdf。由于您感兴趣的是大于或等于 10 次成功,即 10 次或更多成功的概率之和,即 1-cdf。 sf 函数可以采用 numpy 数组作为参数,因此我们传入一个数组作为 n(改变试验次数)。然后,我们查找给出的值大于定义的置信度的试验次数。

import numpy as np
import scipy.stats 
import matplotlib.pyplot as plt


# Defining model parameters
p = 0.5
k = 10
confidence = 0.9
n = np.arange(k, 5*k)

# Generating survival function distribution and computing the number of required trials
binomSurvivalDist = scipy.stats.binom.sf(k, n, p)
nrequired = n[binomSurvivalDist >= confidence][0]

# Plotting the results to Verify that this works
fig, ax = plt.subplots(1, 1, figsize=(12, 10))
x = np.arange(0, nrequired+1, 1)
ax.plot(x, scipy.stats.binom.sf(x, nrequired, p), lw=2)
ax.set_xlabel("Number of Successes", fontsize=16)
ax.set_ylabel("Probability of Getting At Least this Many Success", fontsize=16)
ax.set_title("Distribution for %i Trials" % nrequired, fontsize=18)

print(nrequired)
plt.show()

该图对于计算来说不是必需的,但可以让我们验证该过程是否给出了正确的答案。

关于python - 如何使用库函数 scipy.stats.binom.pmf 返回给定概率的二项分布中的试验次数 (n)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59360763/

相关文章:

python - 如何在Python中运行TCL脚本?

python - 如何在没有 sudo 的情况下安装下载的 Python 包?

python - 如何从 Superbible Opengl 读取、解析 SBM 文件格式

python - 想想 Python - 无法让 tkinter 工作

python - 转置 csv 同时保留 ID

mysql - 比较peewee sql Python中的日期时间

python - Matplotlib 包含文件中的数据

python - 如何使用 PIL 确定具有共享值的像素区域

python - 如何连接两个对象的路径?

python - scipy.optimize.brentq 在简单情况下无法收敛