簡體   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