View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.math4.legacy.stat.interval;
18  
19  import org.apache.commons.math4.legacy.exception.NotPositiveException;
20  import org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException;
21  import org.apache.commons.math4.legacy.exception.NumberIsTooLargeException;
22  import org.apache.commons.math4.legacy.exception.OutOfRangeException;
23  import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
24  
25  /**
26   * Factory methods to generate confidence intervals for a binomial proportion.
27   * The supported methods are:
28   * <ul>
29   * <li>Agresti-Coull interval</li>
30   * <li>Clopper-Pearson method (exact method)</li>
31   * <li>Normal approximation (based on central limit theorem)</li>
32   * <li>Wilson score interval</li>
33   * </ul>
34   *
35   * @since 3.3
36   */
37  public final class IntervalUtils {
38  
39      /** Singleton Agresti-Coull instance. */
40      private static final BinomialConfidenceInterval AGRESTI_COULL = new AgrestiCoullInterval();
41  
42      /** Singleton Clopper-Pearson instance. */
43      private static final BinomialConfidenceInterval CLOPPER_PEARSON = new ClopperPearsonInterval();
44  
45      /** Singleton NormalApproximation instance. */
46      private static final BinomialConfidenceInterval NORMAL_APPROXIMATION = new NormalApproximationInterval();
47  
48      /** Singleton Wilson score instance. */
49      private static final BinomialConfidenceInterval WILSON_SCORE = new WilsonScoreInterval();
50  
51      /**
52       * Prevent instantiation.
53       */
54      private IntervalUtils() {
55      }
56  
57      /**
58       * Create an Agresti-Coull binomial confidence interval for the true
59       * probability of success of an unknown binomial distribution with the given
60       * observed number of trials, successes and confidence level.
61       *
62       * @param numberOfTrials number of trials
63       * @param numberOfSuccesses number of successes
64       * @param confidenceLevel desired probability that the true probability of
65       *        success falls within the returned interval
66       * @return Confidence interval containing the probability of success with
67       *         probability {@code confidenceLevel}
68       * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
69       * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
70       * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
71       * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
72       */
73      public static ConfidenceInterval getAgrestiCoullInterval(int numberOfTrials, int numberOfSuccesses,
74                                                               double confidenceLevel) {
75          return AGRESTI_COULL.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
76      }
77  
78      /**
79       * Create a Clopper-Pearson binomial confidence interval for the true
80       * probability of success of an unknown binomial distribution with the given
81       * observed number of trials, successes and confidence level.
82       * <p>
83       * Preconditions:
84       * <ul>
85       * <li>{@code numberOfTrials} must be positive</li>
86       * <li>{@code numberOfSuccesses} may not exceed {@code numberOfTrials}</li>
87       * <li>{@code confidenceLevel} must be strictly between 0 and 1 (exclusive)</li>
88       * </ul>
89       *
90       * @param numberOfTrials number of trials
91       * @param numberOfSuccesses number of successes
92       * @param confidenceLevel desired probability that the true probability of
93       *        success falls within the returned interval
94       * @return Confidence interval containing the probability of success with
95       *         probability {@code confidenceLevel}
96       * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
97       * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
98       * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
99       * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
100      */
101     public static ConfidenceInterval getClopperPearsonInterval(int numberOfTrials, int numberOfSuccesses,
102                                                                double confidenceLevel) {
103         return CLOPPER_PEARSON.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
104     }
105 
106     /**
107      * Create a binomial confidence interval for the true probability of success
108      * of an unknown binomial distribution with the given observed number of
109      * trials, successes and confidence level using the Normal approximation to
110      * the binomial distribution.
111      *
112      * @param numberOfTrials number of trials
113      * @param numberOfSuccesses number of successes
114      * @param confidenceLevel desired probability that the true probability of
115      *        success falls within the interval
116      * @return Confidence interval containing the probability of success with
117      *         probability {@code confidenceLevel}
118      */
119     public static ConfidenceInterval getNormalApproximationInterval(int numberOfTrials, int numberOfSuccesses,
120                                                                     double confidenceLevel) {
121         return NORMAL_APPROXIMATION.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
122     }
123 
124     /**
125      * Create a Wilson score binomial confidence interval for the true
126      * probability of success of an unknown binomial distribution with the given
127      * observed number of trials, successes and confidence level.
128      *
129      * @param numberOfTrials number of trials
130      * @param numberOfSuccesses number of successes
131      * @param confidenceLevel desired probability that the true probability of
132      *        success falls within the returned interval
133      * @return Confidence interval containing the probability of success with
134      *         probability {@code confidenceLevel}
135      * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
136      * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
137      * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
138      * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
139      */
140     public static ConfidenceInterval getWilsonScoreInterval(int numberOfTrials, int numberOfSuccesses,
141                                                             double confidenceLevel) {
142         return WILSON_SCORE.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
143     }
144 
145     /**
146      * Verifies that parameters satisfy preconditions.
147      *
148      * @param numberOfTrials number of trials (must be positive)
149      * @param numberOfSuccesses number of successes (must not exceed numberOfTrials)
150      * @param confidenceLevel confidence level (must be strictly between 0 and 1)
151      * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
152      * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
153      * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
154      * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
155      */
156     static void checkParameters(int numberOfTrials, int numberOfSuccesses, double confidenceLevel) {
157         if (numberOfTrials <= 0) {
158             throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_TRIALS, numberOfTrials);
159         }
160         if (numberOfSuccesses < 0) {
161             throw new NotPositiveException(LocalizedFormats.NEGATIVE_NUMBER_OF_SUCCESSES, numberOfSuccesses);
162         }
163         if (numberOfSuccesses > numberOfTrials) {
164             throw new NumberIsTooLargeException(LocalizedFormats.NUMBER_OF_SUCCESS_LARGER_THAN_POPULATION_SIZE,
165                                                 numberOfSuccesses, numberOfTrials, true);
166         }
167         if (confidenceLevel <= 0 || confidenceLevel >= 1) {
168             throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUNDS_CONFIDENCE_LEVEL,
169                                           confidenceLevel, 0, 1);
170         }
171     }
172 }