MATH-1421: Code refactoring.

Replaced unnecessary usage of "pow" function.
Reordered some operations.

It fixes the reported case where the lower bound was negative (see unit
test), but it might not be sufficient to avoid the problem in all cases.
This commit is contained in:
Gilles 2017-06-22 03:03:15 +02:00
parent 777af155a6
commit 34adc60660
2 changed files with 10 additions and 4 deletions

View File

@ -36,14 +36,15 @@ public class WilsonScoreInterval implements BinomialConfidenceInterval {
final double alpha = (1.0 - confidenceLevel) / 2;
final NormalDistribution normalDistribution = new NormalDistribution();
final double z = normalDistribution.inverseCumulativeProbability(1 - alpha);
final double zSquared = FastMath.pow(z, 2);
final double zSquared = z * z;
final double zSquaredOverNumTrials = zSquared / numberOfTrials;
final double mean = (double) numberOfSuccesses / (double) numberOfTrials;
final double factor = 1.0 / (1 + (1.0 / numberOfTrials) * zSquared);
final double modifiedSuccessRatio = mean + (1.0 / (2 * numberOfTrials)) * zSquared;
final double factor = 1.0 / (1 + zSquaredOverNumTrials);
final double modifiedSuccessRatio = mean + zSquaredOverNumTrials / 2;
final double difference = z *
FastMath.sqrt(1.0 / numberOfTrials * mean * (1 - mean) +
(1.0 / (4 * FastMath.pow(numberOfTrials, 2)) * zSquared));
(zSquaredOverNumTrials / (4 * numberOfTrials)));
final double lowerBound = factor * (modifiedSuccessRatio - difference);
final double upperBound = factor * (modifiedSuccessRatio + difference);

View File

@ -40,4 +40,9 @@ public class WilsonScoreIntervalTest extends BinomialConfidenceIntervalAbstractT
Assert.assertEquals(0.1242664, confidenceInterval.getUpperBound(), 1E-5);
}
@Test
public void testMath1421() {
double lo = new WilsonScoreInterval().createInterval(19436, 0, 0.95).getLowerBound();
Assert.assertTrue(lo + " < 0", lo >= 0);
}
}