Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement probability distribution function in Java problem

I have a function which is in the form of probability distribution function as below:

formula

Although I discover some lib providing function to obtain the result as the above formula would do; but I am learning to implement it so I would like to do it my self if possible.

Below is what I can think of when implementing the function

public double pdf(double x){
  double mean = mean();
  double variance = variance();
  double base = 1/Math.sqrt(2*Math.PI*variance);
  double pow = -(Math.pow((x-mean), 2)/2*variance);
  return Math.pow(base, pow); 
}

Is this is the right way to implement pdf? Or what parts do I miss?

I appreciate any help.

like image 540
Alex Jones Avatar asked Mar 12 '11 11:03

Alex Jones


2 Answers

Robert Sedgewick is as good as they come:

http://introcs.cs.princeton.edu/22library/Gaussian.java.html

Take a look at his implementation.

You should also know about M. Abramowitz and I. A. Stegun, a wonderful classic for functions like this. It's available for little money from Dover Books. Worth having.

like image 90
duffymo Avatar answered Nov 18 '22 18:11

duffymo


Your pdf method implements the probability density function of the normal distribution, but it appears you want to implement the cumulative normal distribution function (or at least a variation of it). For the normal distribution, this is highly nontrivial because it involves an infinite integral.

You could try numerical integration by using an approach such as the trapezium rule, but I suspect that as you get further and further from the mean, the inaccuracies start to build up.

If you want to implement the cumulative normal distribution function, then there are two approaches I'd recommend:

  • a table of pre-calculated values, or
  • numerical approximations such as those on the Wikipedia page for the normal distribution.
like image 1
Luke Woodward Avatar answered Nov 18 '22 18:11

Luke Woodward