1

I am trying to pass an array element into a recursive function that calculates the factorial and it outputs 0. There is a warning that says that there is an overflow encountered in long_scalars. Whenever I pass a hard coded number into the function, it seems to work fine though. Does anyone know why this is happening or how to fix it?

rand_10 = np.random.randint(100,500,10)

array([173, 171, 375, 432, 393, 334, 268, 341, 183, 270])

def fact(x):
  if x == 1:
    return 1
  else:
    return x * fact(x-1)

fact(rand_10[0])

RuntimeWarning: overflow encountered in long_scalars

Output: 0

Edit: I read through the link provided in the possible duplicate. I still can't figure out how to resolve the issue. How and where should I set the dtype as int64 if that's the resolution to it?

Tony
  • 97
  • 1
  • 9
  • Possible duplicate of: https://stackoverflow.com/questions/7559595/python-runtimewarning-overflow-encountered-in-long-scalars – Dani Mesejo Oct 06 '19 at 21:07
  • 1
    Possible duplicate of [Python RuntimeWarning: overflow encountered in long scalars](https://stackoverflow.com/questions/7559595/python-runtimewarning-overflow-encountered-in-long-scalars) – norok2 Oct 06 '19 at 21:10
  • I read through the link above but still couldn't figure it out. Am I supposed to set the dtype to int64 in the return value of the function? – Tony Oct 06 '19 at 21:17
  • The factorial of 173 is a *314 digit number*. The factorial of the largest number in your sample array, 432, has 953 digits. The largest number your `randint()` call can return has a 1132 digit factorial. Perhaps you should consider using a much, much smaller range of random numbers? – jasonharper Oct 06 '19 at 21:47

1 Answers1

1

Here is the working code:

import numpy as np

rand_10 = np.random.randint(100,500,10, dtype=np.int64)

def fact(x):
    if x == 1:
        return 1
    else:
        return x * fact(x-1)

x = rand_10[0].item()   # method item() to convert the value into a native Python type
print(fact(x))

rand_10[0] returns the type numpy.int64. So, you need to convert it to a native Python type (i.e. int) by using the method item()

Best regards!

codrelphi
  • 1,075
  • 1
  • 7
  • 13