在python中使用统计信息进行二项分布的随机实验

时间:2019-03-12 02:50:22

标签: python numpy statistics data-science

模拟一个随机实验,将硬币抛掷10000次并确定正面数。
提示:使用n = 1p = 0.5定义二项式分布。
使用 scipy.stats中的二项函数。
将随机种子设置为1
从定义的分布中抽取10000元素的样本。
假设值01分别代表Heads和Tails。
计算头数并显示。利用bincount中可用的numpy方法。

我找到了答案,但并非来自scipy.stats软件包,而是来自随机软件包。以下是我的尝试,但答案不符合预期。请帮助我纠正错误。

import scipy as sp
from scipy import stats
import numpy as np
import random

from scipy.stats import binom
data_binom = binom.rvs(n=1,p=0.5,size=10000)

np.random.seed(1)

#print(data_binom)

y = np.bincount(data_binom)
head = print(y[0])
print(head)

4 个答案:

答案 0 :(得分:0)

我得到了我所期望的。不知道是哪个头:4995或5005?

print(y[0])
print(y[1])

4995
5005

这里有更多代码来说明您的折腾:

from scipy.stats import binom
data_binom = binom.rvs(n=1,p=0.5,size=10000)

heads = 0
tails = 0
edges = 0
count = 0

for coin in data_binom:
    count += 1
    if coin == 1:
        heads += 1
    elif coin == 0:
        tails += 1
    else:
        edges += 1

print("Observed " + str(count) + " of coin tossing with heads " + str(heads)
      + ", tails " + str(tails) + ", and edges " + str(edges))

四个测试的结果:

$ python3.7 test.py
Observed 10000 of coin tossing with heads 4989, tails 5011, and edges 0
$ python3.7 test.py
Observed 10000 of coin tossing with heads 5109, tails 4891, and edges 0
$ python3.7 test.py 
Observed 10000 of coin tossing with heads 4968, tails 5032, and edges 0
$ python3.7 test.py 
Observed 10000 of coin tossing with heads 5046, tails 4954, and edges 0

答案 1 :(得分:0)

似乎问题在于您在哪里设置种子。目前,您正在发布样本选择,理想情况下应在样本选择之前完成,如下所示:

import scipy as sp
from scipy import stats
import numpy as np

np.random.seed(1)
from scipy.stats import binomdata_binom = binom.rvs(n=1,p=0.5,size=10000)
#print(data_binom)

y = np.bincount(data_binom)
head = print(y[0])
print(head)

猜猜这就是您的预期输出。干杯!

答案 2 :(得分:0)

from scipy.stats import binom
import numpy as np
b = binom(n=1,p=0.5)
np.random.seed(1)
sample = b.rvs(size=10000)
print(np.count_nonzero(sample==0)) # heads is assumed to be zero

此代码将在您的环境中运行。相信我!

答案 3 :(得分:0)

设置 binom.rvs size=1,然后设置正面概率为 0.5

from scipy.stats import binom
flips=binom.rvs(1000,0.5,size=1)
print(flips)
plt.pie([flips,1000])
plt.legend(['heads','tails'])
plt.show()