nipunasudha
nipunasudha

Reputation: 2607

Non-uniform (biased towards a value) random numbers in JavaScript

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)

Upvotes: 3

Views: 457

Answers (1)

John
John

Reputation: 1341

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>

Upvotes: 3

Related Questions