繁体   English   中英

带有随机数生成器的多态性的Python代码

[英]Python code for polymorphism with random number generator

我想创建一个通用随机变量,其分布取决于特定条件,然后根据保留的分布生成一个随机变量序列。 例如,


if (condition):
    RV = np.random.normal
""" The above command will assign the standard normal distribution to RV. I do not know how to assign the normal distribution with mean $m$ and variance sigma^2.
""" else: RV = np.random.exponential

""" Similar problem here. I do not know how to assign the shape parameter of the exponential distribution.
"""

""" generate a sample of size 10 from the distribution a """ for i in range(0,9): RV.next() # I would like a generic function "next" to generate the next number in the sequence

如果满足条件,以上代码将创建一个具有标准正态分布的随机变量,否则它将为RV分配一个具有单位形状参数的指数生成器。

我想知道如何使用与默认赋值不同的均值(或分布的其他参数)来初始化RV。

使用scipy.stats。 例如

import scipy.stats
r = scipy.stats.uniform() # or other distribution chosen dynamically

random_range = r.rvs(size = 10)

因此,从Haskell之类的语言中就赞扬了部分函数。 基本上,部分函数是一个函数...预填充了一些args

Python在2.5及更高版本中还支持部分功能: https : //docs.python.org/2/library/functools.html#functools.partial

from functools import partial

if (condition):
    RV = partial(np.random.normal, loc=avg, scale=stdev)
else:
    RV = partial(np.random.exponential, scale=scale)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM