001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.math4.legacy.stat.interval; 018 019import org.apache.commons.statistics.distribution.FDistribution; 020 021/** 022 * Implements the Clopper-Pearson method for creating a binomial proportion confidence interval. 023 * 024 * @see <a 025 * href="http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Clopper-Pearson_interval"> 026 * Clopper-Pearson interval (Wikipedia)</a> 027 * @since 3.3 028 */ 029public class ClopperPearsonInterval implements BinomialConfidenceInterval { 030 031 /** {@inheritDoc} */ 032 @Override 033 public ConfidenceInterval createInterval(int numberOfTrials, 034 int numberOfSuccesses, 035 double confidenceLevel) { 036 IntervalUtils.checkParameters(numberOfTrials, numberOfSuccesses, confidenceLevel); 037 double lowerBound = 0; 038 double upperBound = 1; 039 040 final double alpha = 0.5 * (1 - confidenceLevel); 041 042 if (numberOfSuccesses > 0) { 043 final FDistribution distributionLowerBound = FDistribution.of(2.0 * (numberOfTrials - numberOfSuccesses + 1), 044 2.0 * numberOfSuccesses); 045 final double fValueLowerBound = distributionLowerBound.inverseSurvivalProbability(alpha); 046 lowerBound = numberOfSuccesses / 047 (numberOfSuccesses + (numberOfTrials - numberOfSuccesses + 1) * fValueLowerBound); 048 } 049 050 if (numberOfSuccesses < numberOfTrials) { 051 final FDistribution distributionUpperBound = FDistribution.of(2.0 * (numberOfSuccesses + 1), 052 2.0 * (numberOfTrials - numberOfSuccesses)); 053 final double fValueUpperBound = distributionUpperBound.inverseSurvivalProbability(alpha); 054 upperBound = (numberOfSuccesses + 1) * fValueUpperBound / 055 (numberOfTrials - numberOfSuccesses + (numberOfSuccesses + 1) * fValueUpperBound); 056 } 057 058 return new ConfidenceInterval(lowerBound, upperBound, confidenceLevel); 059 } 060}