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?

4
  • Possible duplicate of: stackoverflow.com/questions/7559595/… Commented Oct 6, 2019 at 21:07
  • 1
    Possible duplicate of Python RuntimeWarning: overflow encountered in long scalars Commented Oct 6, 2019 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? Commented Oct 6, 2019 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? Commented Oct 6, 2019 at 21:47

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.