How to generate random numbers biased towards one value in a range?

后端 未结 4 1938
独厮守ぢ
独厮守ぢ 2020-12-08 01:08

Say, if I wanted to generate an unbiased random number between min and max, I\'d do:

var rand = function(min, max) {
    return Mat         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 01:52

    Fun: use the image as the density function. Sample random pixels until you get a black one, then take the x co-ordinate.

    enter image description here

    Code:

    getPixels = require("get-pixels"); // npm install get-pixels
    
    getPixels("distribution.png", function(err, pixels) {
      var height, r, s, width, x, y;
      if (err) {
        return;
      }
      width = pixels.shape[0];
      height = pixels.shape[1];
      while (pixels.get(x, y, 0) !== 0) {
        r = Math.random();
        s = Math.random();
        x = Math.floor(r * width);
        y = Math.floor(s * height);
      }
      return console.log(r);
    });
    

    Example output:

    0.7892316638026386
    0.8595335511490703
    0.5459279934875667
    0.9044852438382804
    0.35129814594984055
    0.5352215224411339
    0.8271261665504426
    0.4871773284394294
    0.8202084102667868
    0.39301465335302055
    

    Scale to taste.

提交回复
热议问题