KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JSci > maths > statistics > BinomialDistribution


1 package JSci.maths.statistics;
2
3 import JSci.maths.ExtraMath;
4
5 /**
6 * The BinomialDistribution class provides an object for encapsulating binomial distributions.
7 * @version 0.1
8 * @author Mark Hale
9 */

10 public final class BinomialDistribution extends ProbabilityDistribution {
11         private int n;
12         private double p;
13
14         /**
15         * Constructs a binomial distribution.
16         * @param trials the number of trials.
17         * @param prob the probability.
18         */

19         public BinomialDistribution(int trials,double prob) {
20                 if(trials<=0)
21                         throw new OutOfRangeException("The number of trials should be (strictly) positive.");
22                 n=trials;
23                 if(prob<0.0 || prob>1.0)
24                         throw new OutOfRangeException("The probability should be between 0 and 1.");
25                 p=prob;
26         }
27         /**
28         * Returns the number of trials.
29         */

30         public int getTrialsParameter() {
31                 return n;
32         }
33         /**
34         * Returns the probability.
35         */

36         public double getProbabilityParameter() {
37                 return p;
38         }
39         /**
40         * Returns the mean.
41         */

42         public double getMean() {
43                 return n*p;
44         }
45         /**
46         * Returns the variance.
47         */

48         public double getVariance() {
49                 return n*p*(1.0-p);
50         }
51         /**
52         * Probability density function of a binomial distribution.
53         * @param X should be integer-valued.
54         * @return the probability that a stochastic variable x has the value X, i.e. P(x=X).
55         */

56         public double probability(double X) {
57                 checkRange(X,0.0,n);
58                 return ExtraMath.binomial(n,X)*Math.pow(p,X)*Math.pow(1.0-p,n-X);
59         }
60         /**
61         * Cumulative binomial distribution function.
62         * @param X should be integer-valued.
63     * @return the probability that a stochastic variable x is less then X, i.e. P(x&lt;X).
64         */

65         public double cumulative(double X) {
66                 checkRange(X,0.0,n);
67                 double sum=0.0;
68                 for(double i=0.0;i<=X;i++)
69                         sum+=probability(i);
70                 return sum;
71         }
72         /**
73     * Inverse of the cumulative binomial distribution function.
74         * @return the value X for which P(x&lt;X).
75         */

76         public double inverse(double probability) {
77                 checkRange(probability);
78                 return Math.floor(findRoot(probability,n/2.0,0.0,n));
79         }
80 }
81
82
Popular Tags