首页 > 解决方案 > 如何在定义函数时将随机数数组传递给 random.choice?

问题描述

我正在尝试编写一个 python 代码来计算随机停止的总和,但是当随机生成的数字的大小超过 5 时遇到问题。

MemoryError:无法为形状(49、53、43、46、52、53、57、52、52)和数据类型 float64 的数组分配 15.5 PiB

在以下代码中:

#Create a function tn.func to calculate randomly stopped sum
import numpy as np
#Define a function
def tn_fun(n):
    return sum(np.random.choice([50, 100, 200], n, replace=True, p=[0.3, 0.5, 0.2]))
N = np.random.poisson(50, 10)
# #Generate 10000 random values of N, using lambda = 50
TN = tn_fun(N)
print('Sample mean of the randomly stopped sum TN is',np.mean(TN))
print('Sample variance of the randomly stopped sum TN is', np.var(TN))

标签: pythonrandomnumpy-ndarray

解决方案


这似乎是你所要求的。

import numpy as np

# How many samples should there be?

# This is uniform between 5000 and 15000.
#N = np.random.randint(5000, 15000)

# This picks one number with Poisson distribution centered at 10000.
N = np.random.poisson(10000, 1)[0]

# Generate them.

TN = np.random.choice( [50,100,200], N, p=[0.3,0.5,0.2] )

print('Sample mean of the randomly stopped sum TN is',np.mean(TN))
print('Sample variance of the randomly stopped sum TN is', np.var(TN))

推荐阅读