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.

3
  • 1
    I'm getting 0.40187757202 from the online calculator. Commented Mar 13, 2020 at 15:17
  • Same here, 0.40187757202 from the online calculator. It looks like your code runs correctly. Commented Mar 13, 2020 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)). Commented Mar 13, 2020 at 18:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.