Javascript中的加权随机数生成器 [英] Weighted Random Number Generator in Javascript
问题描述
我使用以下代码生成随机数:
function getRandomInt(min,max){
返回Math.floor((Math.random()*(max - min + 1))+ min;
}
我想要做的是添加一个有利于范围较低端数字的权重。
我想也许尝试将数字乘以1 /余弦。
这会有效,有没有人知道我怎么做?
<非常感谢!
第一个解决方案
你需要一个包含点(0,0)和(1,1)的函数。例如: x ^ n
当 n> 0 $时c $ c>
Math.pow(1,n)=== 1
和
Math.pow(0, n)=== 0
因此,您只需更改 n
取决于你希望权重如何工作。
- 当
n = 1
:y === x
- 当
n> 1
:y< = x
- 当
0< n< 1
:y> = x
因此,如果您希望较低的值比较高的值更受青睐,只需使用 n> 1
。
var weighted = Math.pow(Math.random(),2);
然后你可以像往常一样缩放结果。
var scaled = Math.floor(加权*(max - min + 1))+ min;
其他函数
同样,你可以使用任何连续函数其中包含点(0,0),(1,1),并且范围和域为[0,1]。
正弦
y = sin(xπ/ 2)
余弦
y = 1 - cos(xπ/ 2)
I am using the following code to generate a random number:
function getRandomInt (min, max) {
return Math.floor((Math.random() * (max - min + 1)) + min;
}
What I want to do is add a weighting that favours the numbers at the lower end of the range.
I thought about maybe trying to multiply the numbers by 1/cosine.
Would this work and does anyone know how I might go about it?
Many thanks!
First Solution
You need a function which contains the points (0, 0) and (1, 1). For instance: x^n
when n > 0
Math.pow(1, n) === 1
And
Math.pow(0, n) === 0
Therefore, you would just change n
depending on how you want the weighting to work.
- When
n = 1
:y === x
- When
n > 1
:y <= x
- When
0 < n < 1
:y >= x
So, if you want lower values to be favored over higher values, simply use n > 1
.
var weighted = Math.pow(Math.random(), 2);
Then you can scale the result as usual.
var scaled = Math.floor(weighted * (max - min + 1)) + min;
Other Functions
Likewise, you could use any continuous function which contains the points (0, 0), (1, 1), and has range and domain of [0, 1].
Sine
y = sin(xπ/2)
Cosine
y = 1 - cos(xπ/2)
这篇关于Javascript中的加权随机数生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!