Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random Number Based on Beta Distribution using Boost

I am trying to use Boost to generate random numbers according to the beta distribution using C++. I have seen many examples online for generating random numbers according to distributions in random.hpp (e.g. this book). However, I cannot seen to translate them to use the beta distribution found in beta.hpp.

Thanks.

like image 829
Erich Peterson Avatar asked Nov 15 '10 04:11

Erich Peterson


People also ask

How do you generate random numbers from a beta distribution?

R = betarnd(A,B) generates random numbers from the beta distribution with parameters specified by A and B . A and B can be vectors, matrices, or multidimensional arrays that have the same size, which is also the size of R .

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.


1 Answers

You'll first want to draw a random number uniformly from the range (0,1). Given any distribution, you can then plug that number into the distribution's "quantile function," and the result is as if a random value was drawn from the distribution. From here:

A general method to generate random numbers from an arbitrary distribution which has a cdf without jumps is to use the inverse function to the cdf: G(y)=F^{-1}(y). If u(1), ..., u(n) are random numbers from the uniform on (0,1) distribution then G(u(1)), ..., G(u(n)) is a random sample from the distribution with cdf F(x).

So how do we get a quantile function for a beta distribution? The documentation for beta.hpp is here. You should be able to use something like this:

#include <boost/math/distributions.hpp>
using namespace boost::math;

double alpha, beta, randFromUnif; 
//parameters and the random value on (0,1) you drew

beta_distribution<> dist(alpha, beta);
double randFromDist = quantile(dist, randFromUnif);
like image 191
btown Avatar answered Oct 05 '22 10:10

btown