4

I'm completing a project euler problem, but this function returns infinity for any value over 40.

from scipy.special import comb
def B(x):
    product = 1
    for i in range(x + 1):
        product *= comb(x, i)
    return product

what I'm getting back

  problem_650.py:10: RuntimeWarning: overflow encountered in double_scalars
  product *= comb(x, i)
  inf

any help with fixing this would be appreciated.

jottbe
  • 4,228
  • 1
  • 15
  • 31

1 Answers1

4

Try this:

def B(x):
    product = 1
    for i in range(x + 1):
        product *= comb(x, i, exact=True)
    return int(product)

B(40)

It most likely is slower, but as you do stuff from project Euler I guess you don't want to approximate the comb values, but use the exact ones.

jottbe
  • 4,228
  • 1
  • 15
  • 31
  • Nicely spotted! – Amadan Jul 04 '19 at 10:39
  • 1
    If exact is False, then floating point precision is used, otherwise exact long integer is computed. – AnkushRasgon Jul 04 '19 at 10:48
  • AnkushRasgon: yes that's it. I guess with exact=False, they use the fact, that the binomial coefficients can be approximated by the normal distribution as a deep result of statistics. – jottbe Jul 04 '19 at 10:55