python - 如何在定义函数时将随机数数组传递给 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))
解决方案
这似乎是你所要求的。
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))
推荐阅读
- c - 重置日志文件后双重释放或损坏(顶部)
- c# - 为什么 IE 的 selenium webdriver 无法单击具有特定 CSS 的 iframe 中的元素?
- javascript - 在数据中使用特殊字符时,Json 解析会出错
- regex - 正则表达式 - 贪婪直到下一场比赛
- r - 如果模式匹配,则为列名添加前缀
- c++ - 将 C++ DLL 导出到 Visual Basic
- json - extract subset of imported json file in vue's data() function
- c# - 在 .NET CORE 中将 View Component 类设为泛型
- python-3.x - 在弹性搜索匹配查询中获取范围 [a, b] 之间的 _score 值
- discord.js - discord.js-commando TypeError:RichEmbed 不是构造函数