I want to generate a number based on a distributed probability. For example, just say there are the following occurences of each numbers:
Number| Count 1 | 150 2 | 40 3 | 15 4 | 3 with a total of (150+40+15+3) = 208 then the probability of a 1 is 150/208= 0.72 and the probability of a 2 is 40/208 = 0.192
How do I make a random number generator that returns be numbers based on this probability distribution?
I'm happy for this to be based on a static, hardcoded set for now but I eventually want it to derive the probability distribution from a database query.
I've seen similar examples like this one but they are not very generic. Any suggestions?
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).
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.
R = random( pd ) returns a random number from the probability distribution object pd . R = random(___, sz1,...,szN ) generates an array of random numbers from the specified probability distribution using input arguments from any of the previous syntaxes, where sz1,...,szN indicates the size of each dimension.
The general approach is to feed uniformly distributed random numbers from 0..1 interval into the inverse of the cumulative distribution function of your desired distribution.
Thus in your case, just draw a random number x from 0..1 (for example with Random.NextDouble()
) and based on its value return
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With