Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在这段代码中生成两次随机数?_Python_Python 3.x_Matplotlib_Histogram - Fatal编程技术网

Python 如何在这段代码中生成两次随机数?

Python 如何在这段代码中生成两次随机数?,python,python-3.x,matplotlib,histogram,Python,Python 3.x,Matplotlib,Histogram,在下面的代码中,我生成随机数,然后计算概率并创建图表。现在,我怎样才能使图形两次,就像我想再次生成随机数,然后再次创建图形一样 #!/usr/bin/env python3 from collections import Counter import numpy as np import matplotlib.pyplot as plt #Random Number Generating x = np.random.randint(low=1, high=100, size=100000)

在下面的代码中,我生成随机数,然后计算概率并创建图表。现在,我怎样才能使图形两次,就像我想再次生成随机数,然后再次创建图形一样

#!/usr/bin/env python3
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt

#Random Number Generating
x = np.random.randint(low=1, high=100, size=100000)


counts = Counter(x)
total = sum(counts.values())
d1 = {k:v/total for k,v in counts.items()}
grad = d1.keys()
prob = d1.values()
print(str(grad))
print(str(prob))
#bins = 20
plt.hist(prob,bins=20, normed=1, facecolor='blue', alpha=0.5)
#plt.plot(bins, hist, 'r--')
plt.xlabel('Probability')
plt.ylabel('Number Of Students')
plt.title('Histogram of Students Grade')
plt.subplots_adjust(left=0.15)

plt.show()

您可以根据需要调用函数

import numpy as np
import matplotlib.pyplot as plt
from collections import Counter

def my_funct():
   np.random.seed(1223) # fixing the seed! but I don't think you need it

   #Random Number Generating
   x = np.random.randint(low=1, high=100, size=100000)
   counts = Counter(x)
   total = sum(counts.values())
   d1 = {k:v/total for k,v in counts.items()}
   grad = d1.keys()
   prob = d1.values()
   print(str(grad))
   print(str(prob))
   #bins = 20
   plt.hist(prob,bins=20, normed=1, facecolor='blue', alpha=0.5)
   #plt.plot(bins, hist, 'r--')
   plt.xlabel('Probability')
   plt.ylabel('Number Of Students')
   plt.title('Histogram of Students Grade')
   plt.subplots_adjust(left=0.15)

   plt.show()
#calling the function twice
my_funct()
my_funct()

将所有内容都放入函数中。调用该函数两次。(您想得到相同的随机数,还是不同的随机数?)如果您想复制精确的图形,请为随机数生成器设置一个显式种子。请参见:@ImportanceOfBeingErnest我从未在python中使用过函数。你能把这个代码用在函数中吗?相同的数字或其生成的随机数并不重要。@JohnColeman在我的代码中,我如何调用这个
numpy.random.seed(seed=None)