CrackerKraken
CrackerKraken

Reputation: 59

Generate a random number with a non-uniform distribution

I have a formula that generates a random integer in a given range [x,y].

rand = Math.floor(x + Math.random()*(y-x+1));

And I would like the generated integer to have a higher chance of being close to the midrange. Here is an interesting approach.

I am trying to adapt that solution to my problem (numbers skewed towards the midrange, not the extremities), but I am struggling with the formula.

beta = Math.sin(Math.random()*Math.PI)^2;
rand = Math.floor(x + beta*(y-x+1));

I do not understand how beta works. According to this graph wouldn't the numbers generated have a higher chance of being closer to 0.5? beta always returns the same number. Didn't I implement Math.random() properly? I swear javascript is messing with me right now.

Upvotes: 1

Views: 798

Answers (1)

zerkms
zerkms

Reputation: 255115

You probably need a

beta = 4 * (rand - 0.5)^3 + 0.5

function or something with a similar shape

Graph

Distribution results: http://jsfiddle.net/4hBqz/

Upvotes: 2

Related Questions