+ 1
Question about abs in Recursion.
So, I'm learning about Recursion in Python, and I came across this example by Sololearn. def factorial(x): if x == 1: return 1 else: return x * factorial(x-1) However, this doesn't allow negative numbers or floats, so I fiddled around making this. def factorial(x): if x == 1: return 1 else: return x * factorial(abs(x-1)) When my factorial function was tested with -5.0, I got the shocking answer of -3600.0, can someone tell me why?
3 Answers
+ 2
Try this and you'll see what's going on:
def factorial(x):
if x == 1:
return 1
else:
print(x)
return x * factorial(abs(x-1))
print(factorial(-5))
It prints all the numbers that end up being multiplied.
When you substract 1 from -5 it ends up being -6, then you get the absolute value which turns it into 6. Then it calculates the factorial of 6 which gets multiplied by the initial -5.
+ 1
First of all, factorials are not defined for negative numbers, although there have been several attempts to generalize the factorial function to every kind of number, such the Gamma function.
Now for your 'fiddled around' code: when you call 'factorial(-5.0)', you're actually computing 'x * factorial(abs(x-1))', with x=-5.0, right? Let's substitute... you want to compute '-5.0 * factorial(abs(-5.0-1))', which is -5.0 * factorial(6.0)... got it?
+ 1
Yes, thank you!