从自定义分布生成随机数 [英] Generate random number from custom distribution

查看:152
本文介绍了从自定义分布生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从自定义分布生成随机数,我已经发现了以下问题:

,但不幸的是,这对我没有帮助,因为该方法建议那里需要一个用于分布函数的公式。我的分布是多个均匀分布的组合,基本上分布函数看起来像直方图。一个例子是:

I am trying to generate random numbers from a custom distribution, i already found this question: Simulate from an (arbitrary) continuous probability distribution but unfortunatly it does not help me since the approach suggested there requires a formula for the distribution function. My distribution is a combination of multiple uniform distributions, basically the distribution function looks like a histogram. An example would be:

f(x) = { 
    0     for  x < 1
    0.5   for  1 <= x < 2
    0.25  for  2 <= x < 4
    0     for  4 <= x
}


推荐答案

您只需要反CDF方法:

You just need inverse CDF method:

samplef <- function (n) {
  x <- runif(n)
  ifelse(x < 0.5, 2 * x + 1, 4 * x)
  }

自己计算CDF以验证:

Compute CDF yourself to verify that:

F(x) = 0                 x < 1
       0.5 * x - 0.5     1 < x < 2
       0.25 * x          2 < x < 4
       1                 x > 4

,因此其倒数为:

invF(x) = 2 * x + 1      0 < x < 0.5
          4 * x          0.5 < x < 1

这篇关于从自定义分布生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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