我正在尝试解决这个问题:
Generate 1,000 random samples of size 50 from population. Calculate the mean of each of these samples (so you should have 1,000 means) and put them in a list norm_samples_50.
我的猜测是我必须使用 randn 函数,但我不能完全猜测如何根据上述问题形成语法。我已完成研究,但找不到合适的答案。
使用 Numpy 的非常有效的解决方案。
import numpy
sample_list = []
for i in range(50): # 50 times - we generate a 1000 of 0-1000random -
rand_list = numpy.random.randint(0,1000, 1000)
# generates a list of 1000 elements with values 0-1000
sample_list.append(sum(rand_list)/50) # sum all elements
Python 一行代码
from numpy.random import randint
sample_list = [sum(randint(0,1000,1000))/50 for _ in range(50)]
为什么要使用 Numpy?它非常高效且非常准确(十进制)。这个库就是为这些类型的计算和数字而创建的。使用标准库中的 random
很好,但速度和可靠性都不尽如人意。