使用python中的stats进行二项分布的随机实验

问题描述 投票:0回答:2

模拟一次投掷硬币10000次的随机实验,并确定头部的数量。 提示:使用n = 1p = 0.5定义二项分布。 使用scipy.stats中的binom函数。 将随机种子设置为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)
python numpy statistics data-science
2个回答
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

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)

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

© www.soinside.com 2019 - 2024. All rights reserved.