How do I generate normal cumulative distribution in Java? its inverse cdf? How about lognormal?

12,370

Solution 1

As it is mentioned here:

Apache Commons - Math has what you are looking for.

More specifically, check out the NormalDistrubitionImpl class.

And no your professor doesn't need to download stuff if you provide him with all the needed libraries.

UPDATE :

If you want to hand code it (I don't know the actual formula), you can check the following link: http://home.online.no/~pjacklam/notes/invnorm/

There are 2 people who implemented it in java: http://home.online.no/~pjacklam/notes/invnorm/#Java

Solution 2

I had had the same problem and find its solution, the following code will give results for cumulative distribution function just like excel do:

 private static double erf(double x)
{
    //A&S formula 7.1.26
    double a1 = 0.254829592;
    double a2 = -0.284496736;
    double a3 = 1.421413741;
    double a4 = -1.453152027;
    double a5 = 1.061405429;
    double p = 0.3275911;
    x = Math.abs(x);
    double t = 1 / (1 + p * x);
    //Direct calculation using formula 7.1.26 is absolutely correct
    //But calculation of nth order polynomial takes O(n^2) operations
    //return 1 - (a1 * t + a2 * t * t + a3 * t * t * t + a4 * t * t * t * t + a5 * t * t * t * t * t) * Math.Exp(-1 * x * x);

    //Horner's method, takes O(n) operations for nth order polynomial
    return 1 - ((((((a5 * t + a4) * t) + a3) * t + a2) * t) + a1) * t * Math.exp(-1 * x * x);
}
public static double NORMSDIST(double z)
{
    double sign = 1;
    if (z < 0) sign = -1;

    double result=0.5 * (1.0 + sign * erf(Math.abs(z)/Math.sqrt(2)));
    return result;
}
Share:
12,370
user1061210
Author by

user1061210

Updated on June 04, 2022

Comments

  • user1061210
    user1061210 almost 2 years

    I am brand new to Java, second day! I want generate samples with normal distribution. I am using inverse transformation.

    Basically, I want to find the inverse normal cumulative distribution, then find its inverse. And generate samples.

    My questions is: Is there a built-in function for inverse normal cdf? Or do I have to hand code?

    I have seen people refer to this on apache commons. Is this a built-in? Or do I have to download it?

    If I have to do it myself, can you give me some tips? If I download, doesn't my prof also have to have the "package" or special file installed?

    Thanks in advance!

    Edit:Just found I can't use libraries, also heard there is simpler way converting normal using radian.