Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random integers with probabilities

I'm a bit confused about how to generate integer values with probabilities.

As an example, I have four integers with their probability values: 1|0.4, 2|0.3, 3|0.2, 4|0.1

How can I generate these four numbers taking into account their probabilities?

like image 632
Headshota Avatar asked Jan 16 '12 08:01

Headshota


People also ask

How do you generate random numbers with probability?

Generate random value with probability Select a blank cell which you will place the random value at, type this formula =INDEX(A$2:A$8,COUNTIF(C$2:C$8,"<="&RAND())+1), press Enter key. And press F9 key to refresh the value as you need.

How do you generate a random number from a given distribution?

Use rand to generate 1000 random numbers from the uniform distribution on the interval (0,1). rng('default') % For reproducibility u = rand(1000,1); The inversion method relies on the principle that continuous cumulative distribution functions (cdfs) range uniformly over the open interval (0,1).


2 Answers

Here's a useful trick :-)

function randomWithProbability() {   var notRandomNumbers = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4];   var idx = Math.floor(Math.random() * notRandomNumbers.length);   return notRandomNumbers[idx]; } 
like image 171
Sergio Tulentsev Avatar answered Sep 25 '22 02:09

Sergio Tulentsev


A simple naive approach can be:

function getRandom(){   var num=Math.random();   if(num < 0.3) return 1;  //probability 0.3   else if(num < 0.6) return 2; // probability 0.3   else if(num < 0.9) return 3; //probability 0.3   else return 4;  //probability 0.1 }
like image 41
bhups Avatar answered Sep 25 '22 02:09

bhups