1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.hipparchus.distribution.discrete;
23
24 import org.hipparchus.exception.LocalizedCoreFormats;
25 import org.hipparchus.exception.MathIllegalArgumentException;
26 import org.hipparchus.special.Beta;
27 import org.hipparchus.util.FastMath;
28 import org.hipparchus.util.MathUtils;
29
30
31
32
33
34
35
36 public class BinomialDistribution extends AbstractIntegerDistribution {
37
38 private static final long serialVersionUID = 20160320L;
39
40 private final int numberOfTrials;
41
42 private final double probabilityOfSuccess;
43
44
45
46
47
48
49
50
51
52
53 public BinomialDistribution(int trials, double p)
54 throws MathIllegalArgumentException {
55 if (trials < 0) {
56 throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_OF_TRIALS,
57 trials);
58 }
59
60 MathUtils.checkRangeInclusive(p, 0, 1);
61
62 probabilityOfSuccess = p;
63 numberOfTrials = trials;
64 }
65
66
67
68
69
70
71 public int getNumberOfTrials() {
72 return numberOfTrials;
73 }
74
75
76
77
78
79
80 public double getProbabilityOfSuccess() {
81 return probabilityOfSuccess;
82 }
83
84
85 @Override
86 public double probability(int x) {
87 final double logProbability = logProbability(x);
88 return logProbability == Double.NEGATIVE_INFINITY ? 0 : FastMath.exp(logProbability);
89 }
90
91
92 @Override
93 public double logProbability(int x) {
94 if (numberOfTrials == 0) {
95 return (x == 0) ? 0. : Double.NEGATIVE_INFINITY;
96 }
97 double ret;
98 if (x < 0 || x > numberOfTrials) {
99 ret = Double.NEGATIVE_INFINITY;
100 } else {
101 ret = SaddlePointExpansion.logBinomialProbability(x,
102 numberOfTrials, probabilityOfSuccess,
103 1.0 - probabilityOfSuccess);
104 }
105 return ret;
106 }
107
108
109 @Override
110 public double cumulativeProbability(int x) {
111 double ret;
112 if (x < 0) {
113 ret = 0.0;
114 } else if (x >= numberOfTrials) {
115 ret = 1.0;
116 } else {
117 ret = 1.0 - Beta.regularizedBeta(probabilityOfSuccess,
118 x + 1.0, numberOfTrials - x);
119 }
120 return ret;
121 }
122
123
124
125
126
127
128
129 @Override
130 public double getNumericalMean() {
131 return numberOfTrials * probabilityOfSuccess;
132 }
133
134
135
136
137
138
139
140 @Override
141 public double getNumericalVariance() {
142 final double p = probabilityOfSuccess;
143 return numberOfTrials * p * (1 - p);
144 }
145
146
147
148
149
150
151
152
153
154 @Override
155 public int getSupportLowerBound() {
156 return probabilityOfSuccess < 1.0 ? 0 : numberOfTrials;
157 }
158
159
160
161
162
163
164
165
166
167 @Override
168 public int getSupportUpperBound() {
169 return probabilityOfSuccess > 0.0 ? numberOfTrials : 0;
170 }
171
172
173
174
175
176
177
178
179 @Override
180 public boolean isSupportConnected() {
181 return true;
182 }
183 }