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

栏目: Html5 · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/29325069/how-to-generate-random-numbers-biased-towards-one-value-in-a-range

说,如果我想在最小和最大值之间生成一个无偏差的随机数,我会做:

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Practice of Programming

The Practice of Programming

Brian W. Kernighan、Rob Pike / Addison-Wesley / 1999-2-14 / USD 49.99

With the same insight and authority that made their book The Unix Programming Environment a classic, Brian Kernighan and Rob Pike have written The Practice of Programming to help make individual progr......一起来看看 《The Practice of Programming》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

在线进制转换器
在线进制转换器

各进制数互转换器

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具