Skip to content Skip to sidebar Skip to footer

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-

Solution 1:

functionProb(){
    var rnd = Math.random(),
        rnd2 = Math.random();
    if(rnd<0.4) return (1 + Math.floor(1000 * rnd2)/100);
    elseif(rnd<0.6) return (11 + Math.floor(1000 * rnd2)/100);
    elseif(rnd<0.9) return (21 + Math.floor(1000 * rnd2)/100);
    elsereturn (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.

Solution 2:

Rewind's solution is great and specifically tailored to OP's quesiton. A more re-usable solution might be:

functiongetNumber(probabilities){
    var rnd = Math.random();
    var total = 0;
    var hit;
    for(var i = 0; i < probabilities.length; i++){
      if(rnd > total && rnd < total + probabilities[i][0]){
           hit = probabilities[i]
      }
      total += probabilities[i][0];
    }
    returnNumber((hit[1] + (Math.random() * (hit[2] - hit[1]))).toFixed(2));
}

varnumber = getNumber(
  [
    //chance, min, max
    [0.4, 1, 10], 
    [0.2,11,20], 
    [0.3,21,30], 
    [0.1,31,35]
  ]
);

console.log(number);

The function will take an array with the probabilities, for each probability you specify the chance, the minimum value for that chance, the maximum value for that chance. It will return a number with two decimals.

https://jsfiddle.net/x237w5gv/

Solution 3:

I guess this

varget1120 = _ => ~~(Math.random()*10)+11,
    get2130 = _ => ~~(Math.random()*10)+21,
    get3135 = _ => ~~(Math.random()*5)+31,
          a = [get3135,get1120,get1120,get2130,get2130,get2130],
        fun;
result = (fun = a[~~(Math.random()*10)]) ? fun() : ~~(Math.random()*10)+1;
console.log(result);

might do it;

Post a Comment for "Get Random Number Based On Probability"