Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers based on a probability

I'm having trouble generating random numbers that do not follow a discrete uniform distribution.

So for example, say I have 5 numbers (to keep it simple), a probability of number k being generated would be k/15. (k = 1 to 5)

My idea is to generate a random number j using rand(), and if this number j is:

1 => then number 1 is generated

2 or 3 => num 2

4 or 5 or 6 => num 3

7 or 8 or 9 or 10 => num 4

11 or 12 or 13 or 14 or 15 => num 5

Now scale this to generating 1-10, 1-100, 1-1000. Does this work the way I intend it to? I've constructed a loop that pretty much does this every time a number needs to be generated, I think it's probably inefficient since it goes up until it finds the j number generated in one of the ranges... What could be a better way to do this?

EDIT: or maybe create an array once with the proper numbers and then pull out with rand() better solution?

like image 771
DillPixel Avatar asked Jun 08 '12 02:06

DillPixel


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.

What is random number generator in statistics?

What is a random number generator? A random number generator is a process that produces random numbers. Any random process (e.g., a flip of a coin or the toss of a die) can be used to generate random numbers. Stat Trek's Random Number Generator uses a statistical algorithm to produce random numbers.

How do you generate random numbers from an arbitrary distribution?

If we want to generate a random sample according to a distribution F, we can generate a uniform random number on (0,1) and invert it by F. This is due to the fact that, if U is uniform on (0,1), then X=F−1(U) is a random variable that follows F.


1 Answers

You seem to be on the right track, but C++ already has a specialized random number distribution for that, std::discrete_distribution

#include <iostream>
#include <vector>
#include <map>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());

    // list of probabilities    
    std::vector<double> p = {0, 1.0/15, 2.0/15, 3.0/15, 4.0/15, 5.0/15};
    // could also be min, max, and a generating function (n/15 in your case?)
    std::discrete_distribution<> d(p.begin(), p.end());

    // some statistics
    std::map<int, int> m;
    for(int n=0; n<10000; ++n) {
        ++m[d(gen)];
    }
    for(auto p : m) {
        std::cout << p.first << " generated " << p.second << " times\n";
    }
}

online demo: http://ideone.com/jU1ll

like image 200
Cubbi Avatar answered Oct 12 '22 20:10

Cubbi