Bob Darren
Bob Darren

Reputation: 107

Need decimals in answer -- Python Recursion

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

Answers (2)

John La Rooy
John La Rooy

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

JoeC
JoeC

Reputation: 1850

typecast your int to float

e.g. float(3)/2 = 1.5

Upvotes: 0

Related Questions