用给定的可能密度函数生成随机数 [英] Generating random numbers with a given probably density function

查看:292
本文介绍了用给定的可能密度函数生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想指定分布的可能是密度函数,然后选取N个随机数从python中的发行版中.我该怎么做?

I want to specify the probably density function of a distribution and then pick up N random numbers from that distribution in python. How do I go about doing that?

推荐答案

通常,您希望具有逆累积概率密度函数.一旦有了,就可以很容易地沿分布生成随机数:

In general, you want to have the inverse cumulative probability density function. Once you have that, then generating the random numbers along the distribution is simple:

import random

def sample(n):
    return [ icdf(random.random()) for _ in range(n) ]

或者,如果您使用NumPy:

Or, if you use NumPy:

import numpy as np

def sample(n):
    return icdf(np.random.random(n))

在两种情况下,icdf是逆累积分布函数,它接受0到1之间的值,并从分布中输出相应的值.

In both cases icdf is the inverse cumulative distribution function which accepts a value between 0 and 1 and outputs the corresponding value from the distribution.

为说明icdf的性质,我们以值10和12之间的简单均匀分布为例:

To illustrate the nature of icdf, we'll take a simple uniform distribution between values 10 and 12 as an example:

  • 概率分布函数在10和12之间为0.5,在其他地方为零

  • probability distribution function is 0.5 between 10 and 12, zero elsewhere

累积分布函数在10以下为0(没有低于10的样本),12在12以上(没有高于12的样本)并且在值之间线性增加(PDF的整数)

cumulative distribution function is 0 below 10 (no samples below 10), 1 above 12 (no samples above 12) and increases linearly between the values (integral of the PDF)

逆累积分布函数仅在0到1之间定义.在0处为10,在12处为1,并且在值之间线性变化

inverse cumulative distribution function is only defined between 0 and 1. At 0 it is 10, at 12 it is 1, and changes linearly between the values

当然,困难的部分是获得逆累积密度函数.它实际上取决于您的分布,有时您可能具有分析功能,有时您可能希望求助于插值.数值方法可能会有用,因为可以使用数值积分来创建CDF,并可以使用插值来将其求反.

Of course, the difficult part is obtaining the inverse cumulative density function. It really depends on your distribution, sometimes you may have an analytical function, sometimes you may want to resort to interpolation. Numerical methods may be useful, as numerical integration can be used to create the CDF and interpolation can be used to invert it.

这篇关于用给定的可能密度函数生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆