3

I am aware that random integers can be generated in JavaScript like this:

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

But what I want is a set of random numbers that are biased towards a specific value.

As an example, if my specific center value is 200, I want a set of random numbers that has a large range, but mostly around 200. Hopefully there will be a function like

biasedRandom(center, biasedness)

nipunasudha
  • 2,427
  • 2
  • 21
  • 46
  • This sounds more like a [maths](https://math.stackexchange.com) problem than a programming problem. – Quentin Oct 16 '17 at 14:28
  • I was hoping maybe there will be a built in way of doing this. I won't get that if this was on the math forum. – nipunasudha Oct 16 '17 at 14:29
  • What do you mean by "mostly"? At least 50% of the time these are close to 200? And how close is close? – MinusFour Oct 16 '17 at 14:32
  • @MinusFour hopefully there will be a function like `biasedRandom(center, biasedness)` ? – nipunasudha Oct 16 '17 at 14:38
  • Duplicate of this question, although there could be many other ways to do this than the accepted answer: https://stackoverflow.com/questions/29325069/how-to-generate-random-numbers-biased-towards-one-value-in-a-range – Nick Oct 16 '17 at 14:49

1 Answers1

3

It sounds like a Gaussian distribution might be about right here.

This stackoverflow post describes how to produce something that is Gaussian in shape. We can then scale and shift the distribution by two factors;

  • The mean (200 in this case) which is where the distribution is centred
  • The variance which gives control over the width of the distribution

I have included a histogram of the generated numbers (using plotly) in my example so you can easily see how varying these two parameters v and mean affects the numbers generated. In your real code you would not need to include the plotly library.

// Standard Normal variate using Box-Muller transform.
function randn_bm() {
    var u = 0, v = 0;
    while(u === 0) u = Math.random(); //Converting [0,1) to (0,1)
    while(v === 0) v = Math.random();
    return Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v );
}

//generate array
// number of points
let n = 50;
// variance factor
let v = 1;
// mean
let mean = 200;
let numbers = []
for (let i=0; i<n;i++){
 numbers.push(randn_bm())
}
// scale and shift
numbers = numbers.map( function (number){ return number*v + mean})

// THIS PURELY FOR PLOTTING
var trace = {
    x: numbers,
    type: 'histogram',
  };
var data = [trace];
Plotly.newPlot('myDiv', data);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv"></div>
John
  • 1,313
  • 9
  • 21