我想出了解决不导入numpy模块的原始问题的方法,但是我不太了解我还需要导入/添加什么才能使此代码正常工作。我在python 3中,此代码是用PyCharm编写的。我将概率更改为p以防止未声明它的冲突链接到此处的教程文章the site i got it from
import numpy as np
def coinFlip(p):
#perform the binomial distribution (returns 1 or 0)
result = np.random.binomial (1 , p)
#return flip to be added to numpy array
return result
'''Main Area'''
#probability of heads vs. tails. this can be changed
p = .5
#num of flips required. this can be changed
n = 10
#initiate array
FullResults = np.arrange(n)
#perform the desired number of flips required probability set above
for i in range(0, n):
fullResults[i] = coinFlip(p)
i+=1
#print results
print("probability is set to ", p)
print("Tails = 0, Heads = 1: ", fullResults)
#Total up heads and tails for easy user experience
print("head count: ", np.count_nonzero(fullResults == 1))
print("Tail count: ", np.count_nonzero(fullResults == 0))
我必须进行两个小修改-
我用零初始化了数组fullResults
import numpy as np
def coinFlip(p):#执行二项式分布(返回1或0)结果= np.random.binomial(1,p)#return将翻转添加到numpy数组返回结果
'''主要区域''
p = .5
n = 10
FullResults = np.arange(n)
fullResults = np.zeros(n)对于范围(0,n)中的i:fullResults [i] = coinFlip(p)i + = 1
print(“概率设置为”,p)print(“ Tails = 0,Heads = 1:”,fullResults)
print(“ head count:”,np.count_nonzero(fullResults == 1))print(“尾数:”,np.count_nonzero(fullResults == 0))>
这里是输出-
probability is set to 0.5
Tails = 0, Heads = 1: [0. 0. 0. 1. 1. 1. 0. 0. 0. 1.]
head count: 4
Tail count: 6