这是一种方法:
即,以伪:
变量: 最小值= 0 最大= 100 偏差= 67(N) 影响力= 1(D)[0.0,1.0] 式: rnd = random()x(最大-最小)+最小 混合= random()x影响 值 = rnd x(1-混合)+偏差x混合
可以使用辅助因子来降低混合因子,以设置其应影响的程度(即mix * factor
,因子为[0,1])。
这将绘制有偏的随机范围。上限带为1,下限为0.75。偏置在此设置为范围的2/3。底带没有(故意)偏差进行比较。
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>
非常好。感谢您的演示。
@ c00000fd没问题!我忘了提一下,如果偏差大于1并限制混合结果,则偏差可能会更具影响力。但是您可能已经看到了。祝您的项目好运!
如果我希望值为1或0,但我希望结果为67%1s,会发生什么?