Skip to content

Instantly share code, notes, and snippets.

@eddking
Created October 24, 2016 13:06
Show Gist options
  • Save eddking/af7075066ea7cc012cf54b96c7662a7b to your computer and use it in GitHub Desktop.
Save eddking/af7075066ea7cc012cf54b96c7662a7b to your computer and use it in GitHub Desktop.
Utility for calculating the cumulative binomial distribution in ruby
module CumulativeBinomialDistribution
extend self
# s = successes
# p = probability of success per trial
# n = number of trials
def normal_estimate(s, p, n)
u = n * p
o = (u * (BigDecimal.new('1')-p)) ** BigDecimal.new('0.5')
# continuity correction
s = s + BigDecimal.new('0.5')
return BigDecimal.new('0.5') * (BigDecimal.new('1') + erf((s-u)/(o * BigDecimal.new('2') ** BigDecimal.new('0.5'))))
end
def erf(z)
t = BigDecimal.new('1') / (BigDecimal.new('1') + BigDecimal.new('0.5') * z.abs)
# use Horner's method
ans = BigDecimal.new('1') - t * BigMath.exp( -z*z - BigDecimal.new('1.26551223') +
t * ( BigDecimal.new('1.00002368') +
t * ( BigDecimal.new('0.37409196') +
t * ( BigDecimal.new('0.09678418') +
t * ( BigDecimal.new('-0.18628806') +
t * ( BigDecimal.new('0.27886807') +
t * ( BigDecimal.new('-1.13520398') +
t * ( BigDecimal.new('1.48851587') +
t * ( BigDecimal.new('-0.82215223') +
t * ( BigDecimal.new('0.17087277')))))))))), 30)
if z >= BigDecimal.new('0')
return ans
else
return -ans
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment