ReasonPlay - 1 year ago 92
Javascript Question

# Get random number based on probability

I was wondering to get a random number with two decimal places based on probability for example:

``````40% to get number from 1-10
20% to get number from 11-20
30% to get number from 21-30
10% to get number from 31-35
``````

``````function Prob(){
var rnd = Math.random(),
rnd2 = Math.random();
if(rnd<0.4) return (1 + Math.floor(1000 * rnd2)/100);
else if(rnd<0.6) return (11 + Math.floor(1000 * rnd2)/100);
else if(rnd<0.9) return (21 + Math.floor(1000 * rnd2)/100);
else return (31 + Math.floor(500 * rnd2)/100);
}
``````

You need two random numbers, so I calculate them at the start. I then use the if-else loops to cycle through your 40%, 20%, 30% and 10% (adding them up as I go). Note: Math.random returns a number between 0 and 1. Then for each catagory I use the SECOND random number to get in the range you have said - floor it to make sure it is an integer and add the starting number of each range. Note: the range of your last one is just 5.

I should explain, you must use two random numbers, otherwise the range of the second number would be dependent on which category you are in.

I have to do the 1000 * rnd2 in the floor and then divide by 100 outside to get the 2 decimal place you ask for.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download