我想在指数分布的背景下,从对数正态分布生成随机数,如下所示:
我有100个从1到25的整数(比如位置)。这些整数是从我自己的类指数分布中生成的。
在这个地方,我想分发N个项目。但这些项目有自己的对数正态分布,有一些模式(在1到25之间)和标准偏差(从1到7)。我的代码是这样工作的:
我有一个称为variable_vec
的位置数组,我知道N称为N
,我知道模式称为pref_value
,我知道标准差称为power_of_preference
。
首先,我将从pref_value
和power_of_preference
计算shape
和scale
参数。我的进步是这样的:
unique_localities = np.unique(np.array(vec_of_variable)) #all values of localities
res1 = [0 for i in range(len(unique_localities))]
res = [0 for i in range(len(vec_of_variable))] #this will be desired output
for i in range(len(res1)):
res1[i] = stats.lognorm.pdf(unique_localities[i], shape, 0, scale) #pdfs of values of localities
res1 = np.array([x/min(res1) for x in res1]) #here is the problem, min(res1) could be zero, see text
res1 = np.round(res1)
res1 = np.cumsum(res1)
item = 0
while item < N:
r = random.uniform(0, max(res1))
site_pdf_value_vec = [x for x in res1 if x >= r]
site_pdf_value = min(site_pdf_value_vec) #this is value of locality where Ill place one item
代码还在继续,但关键部分在这里。简单地说,位置的logNormpdf值是我将物品放在那个位置的“概率”。这就是我需要pdf值的原因。
PS:这个方法是我的主管批准的,所以我不想改变它。
问题是,这有时会发生,那就是min(res1) = 0
。然后除以零,res1
就变成了无穷大数组。0到25之间的x
的对数正态分布永远不会是零,但它可能非常接近。我认为这个问题是这些pdf值中的一个太接近于零,所以python会将其round
为零。
我的问题是,如何在我的代码中避免在res1
中得到零?我的想法是在python中用最小的正浮点数代替零,但我不知道这个值。还是有另一种更优雅的解决方案?
寻求帮助。
PS:有人可能会考虑不取res1
的反转值,问题的步骤看起来是超流的。但这是控制,这些值中的最小值不是零。换句话说,每个位置都必须有一个“区间”“概率”,如果一个pdf为零,则它的概率不是区间,而是一个数字。
发布于 2017-04-20 14:02:26
计算lognorm.logpdf
而不是lognorm.pdf
,然后在日志空间中工作。对于舍入为零的非常小的概率,这应该具有更好的准确性。
https://stackoverflow.com/questions/43520282
复制相似问题