加权随机数(无预定义值!) [英] Weighted random number (without predefined values!)
问题描述
当前,我需要一个给出加权随机数的函数. 它应该在两个双精度数/整数之间选择一个随机数(例如4和8),而中间的数值(6)将平均出现,大约是限制器值4和8的两倍. 如果这仅是整数,则可以使用变量和自定义概率来预定义值,但是我需要该函数给出一个至少含两位数的双精度数字(表示成千上万个不同的数字)!
currently I'm needing a function which gives a weighted, random number. It should chose a random number between two doubles/integers (for example 4 and 8) while the value in the middle (6) will occur on average, about twice as often than the limiter values 4 and 8. If this were only about integers, I could predefine the values with variables and custom probabilities, but I need the function to give a double with at least 2 digits (meaning thousands of different numbers)!
我使用的环境是"Game Maker",它提供各种基本的随机生成器,但不提供加权的生成器.
The environment I use, is the "Game Maker" which provides all sorts of basic random-generators, but not weighted ones.
有人可以带领我朝着正确的方向实现这一目标吗?
Could anyone possibly lead my in the right direction how to achieve this?
提前谢谢!
推荐答案
两个独立的连续均匀(0,1)的和U1
和U2
的总和具有一个介于0和2之间的连续对称三角形分布.分布的峰值在1,并且在两端逐渐减小到零.通过将比例缩放2并加4,即4 + 2*(U1 + U2)
,我们可以轻松地将其转换为(4,8)范围.
The sum of two independent continuous uniform(0,1)'s, U1
and U2
, has a continuous symmetrical triangle distribution between 0 and 2. The distribution has its peak at 1 and tapers to zero at either end. We can easily translate that to a range of (4,8) via scaling by 2 and adding 4, i.e., 4 + 2*(U1 + U2)
.
但是,您不希望端点的高度为零,而希望峰高的一半.换句话说,您想要一个三角形位于矩形的底部(即均匀的)上,端点的高度为h
,中间的高度为2h
.这使生活变得容易,因为三角形必须在矩形底边上方有一个高度为h
的峰,而高度为h
的三角形的底边和高度为h
的矩形的面积为一半.因此,您的概率的2/3在底数中,而1/3在三角形中.
However, you don't want a height of zero at the endpoints, you want half the peak's height. In other words, you want a triangle sitting on a rectangular base (i.e., uniform), with height h
at the endpoints and height 2h
in the middle. That makes life easy, because the triangle must have a peak of height h
above the rectangular base, and a triangle with height h
has half the area of a rectangle with the same base and height h
. It follows that 2/3 of your probability is in the base, 1/3 is in the triangle.
组合以上元素将导致以下伪代码算法.如果rnd()
是一个返回连续统一(0,1)随机数的函数调用:
Combining the elements above leads to the following pseudocode algorithm. If rnd()
is a function call that returns continuous uniform(0,1) random numbers:
define makeValue()
if rnd() <= 2/3 # Caution, may want to use 2.0/3.0 for many languages
return 4 + (4 * rnd())
else
return 4 + (2 * (rnd() + rnd()))
我使用该值计算出一百万个值并绘制直方图:
I cranked out a million values using that and plotted a histogram:
这篇关于加权随机数(无预定义值!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!