我想回答这个问题:
从总体中生成1,000个大小为50的随机样本。计算每个样本的平均值(因此您应该有1,000个平均值),并将它们放入列表norm_samples_50中。
我的猜测是我需要使用randn函数,但我无法根据上述问题来形成语法。我已经进行了研究,但找不到符合要求的答案。
我想回答这个问题:
从总体中生成1,000个大小为50的随机样本。计算每个样本的平均值(因此您应该有1,000个平均值),并将它们放入列表norm_samples_50中。
我的猜测是我需要使用randn函数,但我无法根据上述问题来形成语法。我已经进行了研究,但找不到符合要求的答案。
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
也可以,但速度和可靠性远不如Numpy。
sum
函数并不是很高效。 - user202729import random
# Creating a population replace with your own:
population = [random.randint(0, 1000) for x in range(1000)]
# Creating the list to store all the means of each sample:
means = []
for x in range(1000):
# Creating a random sample of the population with size 50:
sample = random.sample(population,50)
# Getting the sum of values in the sample then dividing by 50:
mean = sum(sample)/50
# Adding this mean to the list of means
means.append(mean)