【发布时间】:2020-06-02 04:10:42
【问题描述】:
我正在尝试实现 CLT(中心极限定理)时数据分布的差异,比较两种方法:一种使用纯 Python,另一种使用 Numpy。
这是我的代码:
from numpy.random import seed
from numpy.random import randint
from numpy import mean
import matplotlib.pyplot as plt
import random
# [With Numpy]
#
# Generate 1000 samples of 50 men, from 60 to 90 Kilos and calculate the mean
# of each sample, at once.
seed(1)
means = [mean(randint(60, 90, 50)) for _i in range(1000)]
# [Without Numpy]
#
# Generate 1000 samples of 50 men, from 60 to 90 Kilos.
# Calculate the mean of each sample, storing on a separated list.
random.seed(1)
samples = list()
for i in range(0, 1000):
samples.append([random.randint(60, 90) for n in range(50)])
means_without_numpy = [sum(s) / len(s) for s in samples]
# Plot distributions of sample means, side by side.
plt.subplot(1, 2, 1)
plt.title("Numpy")
plt.hist(means)
plt.subplot(1, 2, 2)
plt.title("Pure Python")
plt.hist(means_without_numpy)
plt.show()
print(f"The mean of means: {mean(means)}")
print(f"The mean of means (without numpy): {mean(means_without_numpy)}")
此代码在关闭它们后会生成以下直方图和一条消息:
$ python3 clt_comparisson.py
The mean of means: 74.54001999999998
The mean of means (without numpy): 74.94394
我的问题是:
- 分布(来自随机数据集的平均值)是否受到每个模块(
random和numpy)提供随机数据的方式的影响? - 如果第一个问题是正确的:既然我提供
1作为种子,它们是否应该生成相同的随机数据集,因为它们具有相同的种子值?
【问题讨论】:
-
“它们是否应该生成相同的随机数据集,因为它们具有相同的种子值” - 不,这不是播种的工作原理。
-
种子(按范围或值)并不意味着使用相同的 PRNG 算法。决定序列质量的是实际算法。 - en.wikipedia.org/wiki/Pseudorandom_number_generator
-
@user2357112supportsMonica - 使用相同种子两次的相同算法应该产生相同的结果。创建
r1 = random.Random(b'My standard seed')和r2 = random.Random(b'My standard seed'),两者都会产生相同的数字。r1.randint(0, 100000) == r2.randint(0, 100000).
标签: python numpy matplotlib random random-seed