Reputation: 117
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?
Upvotes: 1
Views: 96
Reputation: 1065
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!
Upvotes: 1