From ebbc3300e51388c57ccd4718ae4889c686d64e2b Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Mon, 22 Feb 2021 03:17:06 -0800 Subject: [PATCH] Fixed Math::DomainError with continuity correction --- lib/wilson_score.rb | 6 ++---- test/wilson_score_test.rb | 10 ++++++++++ wilson_score.gemspec | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/lib/wilson_score.rb b/lib/wilson_score.rb index 639f059..6251cdb 100644 --- a/lib/wilson_score.rb +++ b/lib/wilson_score.rb @@ -16,10 +16,8 @@ def self.interval(k, n, *args) if correction # continuity correction a = 2 * (n + z2) b = 2*n*phat + z2 - c = z * Math.sqrt(z2 - 1.0/n + 4*n*phat*(1 - phat) + (4*phat - 2)) + 1 - d = z * Math.sqrt(z2 - 1.0/n + 4*n*phat*(1 - phat) - (4*phat - 2)) + 1 - lower = phat == 0 ? 0 : [0, (b - c) / a].max - upper = phat == 1 ? 1 : [1, (b + d) / a].min + lower = phat == 0 ? 0 : [0, (b - (z * Math.sqrt(z2 - 1.0/n + 4*n*phat*(1 - phat) + (4*phat - 2)) + 1)) / a].max + upper = phat == 1 ? 1 : [1, (b + (z * Math.sqrt(z2 - 1.0/n + 4*n*phat*(1 - phat) - (4*phat - 2)) + 1)) / a].min lower..upper else a = 1 + z2 / n diff --git a/test/wilson_score_test.rb b/test/wilson_score_test.rb index 5f98919..4564829 100644 --- a/test/wilson_score_test.rb +++ b/test/wilson_score_test.rb @@ -54,6 +54,16 @@ def test_continuity_correction_one_three assert_in_delta 0.8747, interval.last end + def test_continuity_correction_p_zero + assert_equal 0, WilsonScore.interval(0, 25, confidence: 0.8).first + assert_equal 1, WilsonScore.rating_interval(1, 25, 1..5, confidence: 0.8).first + end + + def test_continuity_correction_p_one + assert_equal 1, WilsonScore.interval(25, 25, confidence: 0.8).last + assert_equal 5, WilsonScore.rating_interval(5, 25, 1..5, confidence: 0.8).last + end + def test_rating interval = WilsonScore.rating_interval(5, 1, 1..5, correction: false) assert_in_delta 1.8262, interval.first diff --git a/wilson_score.gemspec b/wilson_score.gemspec index c788109..2ca453b 100644 --- a/wilson_score.gemspec +++ b/wilson_score.gemspec @@ -18,7 +18,7 @@ Gem::Specification.new do |spec| spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] - spec.add_development_dependency "bundler", "~> 1.3" + spec.add_development_dependency "bundler" spec.add_development_dependency "rake" spec.add_development_dependency "minitest" end