Reputation: 107
def f(x):
if x == 1:
return 1
elif x > 1:
z = ((x**(x-1))/(x-1))
b = z + f(x-1)
return b
How can I get a number with decimal points? I've tried using float, but this doesn't work either. For example, if i do f(4) i get 28, but i want something like 28.833. Any advice?
Upvotes: 0
Views: 44
Reputation: 304375
If you are using python2, the result of int/int
is truncated to an int
If that is the problem, it should be sufficient to call f(4.0)
since then x-1
etc will be floats and so force a floating point division
Alternatively you can put
from __future__ import division
as the first line of you module
>>> def f(x):
... if x == 1:
... return 1
... elif x > 1:
... z = ((x**(x-1))/(x-1))
... b = z + f(x-1)
... return b
...
>>> f(4)
28
>>> f(4.0)
28.833333333333332
Upvotes: 1