javascript – 如何產生偏向一個範圍內的一個值的隨機數?
說,如果我想在最小和最大值之間生成一個無偏差的隨機數,我會做:
var rand = function(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; };
但是,如果我想在最小和最大值之間產生一個隨機數,但是更偏向於min和max之間的值N到D度?最好用概率曲線來說明它:
這是一種方法:
>獲取最小 – 最大範圍內的隨機數
>獲取隨機的歸一化混合值
>隨機混合隨機混合偏差
即,偽:
<b>Variables:</b> min = 0 max = 100 bias = 67(N) influence = 1(D) [0.0, 1.0] <b>Formula:</b> rnd = random() x (max - min) + min mix = random() x influence <b>value</b> = rnd x (1 - mix) + bias x mix
混合因子可以用次要因子來減少,以設定它應該影響多少(即因子為[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>
http://stackoverflow.com/questions/29325069/how-to-generate-random-numbers-biased-towards-one-value-in-a-range