🔴 平均多少个[0,1]的随机数之和才大于1?\#
平均多少个[0,1]的随机数之和才大于1?
对于这个问题,我们的第一反应可能是2个,因为在\([0,1]\)之间随机选择一个数,它的期望是\(0.5\),因此选两个随机数,它们的期望是\(1\)。但是这里就需要注意了,我们要的结果是大于1,因此对于为\(1\)的情况,我们需要再取一个数,因此在这里只要取到一个不为\(0\)的数(当然,这里取到\(0\)的概率也为\(0\),只不过这并不代表不可能发生),我们就能使和大于\(1\),因此在这种情况下,实际我们是取了3个数。那么现在这个问题就变得有意思了
答案是\(e\)个.
我们可以用Python验证一下答案:
import numpy as np
import matplotlib.pyplot as plt
# We gonna use this algorithm
random_number = np.random.rand()
def main():
def over_one():
count, sum = 0, 0
while sum < 1:
count += 1
sum += np.random.rand()
return count
def repeat(num = 10000):
count_all = 0
for _ in range(int(num)):
count_all += over_one()
return count_all / num
pace = 100
x = np.linspace(10000, 100000, pace)
y = np.array([repeat(i) for i in x])
print("平均次数为: ", y.mean())
plt.plot(x, y)
plt.axhline(y = y.mean(), color = 'r', linestyle = '--')
plt.show()
if __name__ == "__main__":
main()