0

How can I get the best precision in an equation involving factorial, division and squaring?

As an example, I'm trying to make the binomical probability calculator in python:

# n: Number of trials
# X: Number of successes
# p: Probability of success on a single trial   
def binominal(n, X, p): 
    return ( math.factorial(n) / (math.factorial(n - X) * math.factorial(X)) ) * ((p**X) * ((1-p)**(n-X)))

print(binominal(5, 1, 0.166666666666))

Output:

0.4018775720164609

Now comparing with the binomial probability gained from an online calculator:

0.3468305983

My precision is way off. How can I get a better precision? I looked at the Python documentation and then tried to use the Decimal form instead, I didn't really get a better result from that.

halfer
  • 19,824
  • 17
  • 99
  • 186
jubibanna
  • 1,095
  • 9
  • 21
  • 1
    I'm getting `0.40187757202` from the online calculator. – alec Mar 13 '20 at 15:17
  • Same here, `0.40187757202` from the online calculator. It looks like your code runs correctly. – ywbaek Mar 13 '20 at 15:22
  • The main thing to watch out for here is that intermediate quantities such as n! can overflow even if the final result won't. Try computing the logarithm of the binomial instead -- note that log(n!) is a simple summation. There might be a built-in function for the logarithm of the gamma function (remember n! = gamma(n + 1)). – Robert Dodier Mar 13 '20 at 18:24

0 Answers0