3

I need to use beta distribution Beta(a, b) to generate a random number from 0 to 1.

I found Class BetaDist, which has constructor BetaDist(double alpha, double beta) which constructs a BetaDist object with parameters α = alpha and β = beta and default domain (0, 1).

But, I cannot find a method that can use just alpha and beta to return a randomly draw x (0, 1) using the BetaDist object.

I read another post on stackoverflow say: 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).

BetaDist class does have cdf(double x) method, yet I am still lost on what to do next. I haven't learn statistics, and the above post is still too complicated for me.

thank you very much.

user1864404
  • 31
  • 1
  • 2

1 Answers1

2

I just met the same issue as you did. The scheme you mentioned is valid, which I just tested in my case.

The procedure is as follows:

  1. generate a beta distribution--beta with parameter alpha and beta;
  2. generate a random number from uniform distribution --x;
  3. call the inverse cdf to acquire the random number of beta distribution--b, here "x" is used as function input and the inverse cdf can return the random number you want. Notice: the beta distribution should have an inverse cdf to do this, rather than just cdf.

    import org.apache.commons.math3.distribution.BetaDistribution;
    
    public class test {
        /**
         * @param args
         */
        public static void main(String[] args) {
            double x;
            double b;
            BetaDistribution beta = new BetaDistribution(40.0, 40.0);
            for (int i = 0; i < 100; i++) {
                x = Math.random();
                b = beta.inverseCumulativeProbability(x);
                System.out.println(b);
            }
        }
    }
    
azurefrog
  • 10,785
  • 7
  • 42
  • 56
  • 5
    Actually, if you're already using the Apache commons BetaDistribution, you can just do beta.sample(). It inherits the sample method from AbstractRealDistribution. – obuzek May 15 '13 at 23:44