gpt4 book ai didi

javascript - 如何生成一个范围内偏向一个值的随机数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:17:02 24 4
gpt4 key购买 nike

比如说,如果我想生成一个介于 minmax 之间的无偏随机数,我会这样做:

var rand = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};

但是如果我想生成一个介于 minmax 之间但更偏向 N 介于 min 之间的随机数怎么办max 达到 D 的程度?最好用概率曲线来说明:

enter image description here

最佳答案

这是一种方法:

  • 获取最小-最大范围内的随机数
  • 获取随机归一化混合值
  • 在随机混合的基础上混合随机和偏差

即,伪:

Variables:  min = 0  max = 100  bias = 67      (N)  influence = 1  (D) [0.0, 1.0]Formula:  rnd = random() x (max - min) + min  mix = random() x influence  value = rnd x (1 - mix) + bias x mix

The mix factor can be reduced with a secondary factor to set how much it should influence (ie. mix * factor where factor is [0, 1]).

Demo

This will plot a biased random range. The upper band has 1 as influence, the bottom 0.75 influence. Bias is here set to be at 2/3 position in the range.The bottom band is without (deliberate) bias for comparison.

var ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "red"; ctx.fillRect(399,0,2,110); // draw bias target
ctx.fillStyle = "rgba(0,0,0,0.07)";

function getRndBias(min, max, bias, influence) {
var rnd = Math.random() * (max - min) + min, // random in range
mix = Math.random() * influence; // random mixer
return rnd * (1 - mix) + bias * mix; // mix full range and bias
}

// plot biased result
(function loop() {
for(var i = 0; i < 5; i++) { // just sub-frames (speedier plot)
ctx.fillRect( getRndBias(0, 600, 400, 1.00), 4, 2, 50);
ctx.fillRect( getRndBias(0, 600, 400, 0.75), 55, 2, 50);
ctx.fillRect( Math.random() * 600 ,115, 2, 35);
}
requestAnimationFrame(loop);
})();
<canvas width=600></canvas>

关于javascript - 如何生成一个范围内偏向一个值的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29325069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com