如何在c++/java中生成一组遵循一定分布的值?
例如,我有一个 pdf f(x) = 1/25 - x/1250(从 x = 0 到 50); 我的问题是如何生成一组满足给定pdf的值 请给出如何用c++或java实现的想法。 非常感谢。
For example, I have a p.d.f f(x) = 1/25 - x/1250 (from x = 0 to 50);
My question is that how to generate a set of values that satisfy the given p.d.f.
Please give an idea about how to implement in c++ or java.
Thanks so much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不知道直接从pdf,但你可以将pdf转换为cdf(通过集成),然后使用
生成这样的
u
后,找到满足cdf(x) = u
的x
。x
就是您想要的值。I don't know about directly from a pdf, but you can convert a pdf to a cdf (by integrating) and then use inverse transform sampling. This assumes that you have a technique to generate a random number
u
in[0, 1]
(e.g.Math.random()
in Java).Once you have generated such a
u
, find anx
such thatcdf(x) = u
. Thatx
is the value that you want.您的函数类似于
f(x) := 1 - x
。对于这种情况,我执行了以下操作:f
来生成F
。F
,使其域为[0;1)
,产生NF
。NF
得到dist
。然后我使用以下代码来检查结果:
生成的图像对我来说看起来相当不错。
Your function is similar to
f(x) := 1 - x
. For that case I did the following:f
to yieldF
.F
so that its domain is[0;1)
, yieldingNF
.NF
to yielddist
.Then I used the following code to check the result:
The resulting image looked pretty good to me.
如果您的值集是离散的,则文章 "A 中描述了有效的算法生成具有给定分布的随机数的线性算法”。该算法包含一个简单的伪代码,时间为 O(n),其中 n 是集合大小。
当 pdf 不是离散的(如您的示例中所示)时,请参阅 “蒙特卡洛简介”中的第 5.1 节模拟”。
If your values-set is discrete, a valid algorithm is described in the article "A Linear Algorithm For Generating Random Numbers With a Given Distribution". The algorithm contains a simple pseudo-code, and has O(n) time, where n is the set size.
When the pdf is not discrete, as in your example, see section 5.1 in "Introduction to Monte Carlo Simulation".