Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating exp(x) with the use of recursion in Python [duplicate]

I'm attempting to calculate e^x using recursion, e^x = e^(x/2)*e^(x/2), and the third order Maclaurin expansion for e^x and the script keeps returning 1. I'm not looking for a higher accuracy solution, just simply to understand where the script goes wrong : )

My thought is that with enough iterations it should end up with (1+x/N+(x/N)^2/2)^N when the function value goes below the limit.

def exp(x):
      if abs(x)<0.0001:
            return 1+x+x**2/2
      else:
            y=exp(x/2)
            return y*y
like image 267
Skentuey Avatar asked Jul 16 '15 20:07

Skentuey


2 Answers

Try this instead (note the 2.0 in the recursive call):

def exp(x):
    if abs(x) < 0.0001:
        return 1 + x + x**2 / 2.0
    else:
        y = exp(x / 2.0)
        return y * y

It is failing because if you pass an integer in for x, say 1, then x / 2 does integer division (in python 2.x), which would result in 0 instead of 0.5. By using x / 2.0, it forces python to use float division.

like image 195
Jake Griffin Avatar answered Oct 22 '22 10:10

Jake Griffin


def exp(x):
    if abs(x)<0.0001:
        return 1+x+(x**2)/2.0
    else:
        y=exp(x/2.0)
        return y*y

Integer division truncates. You need floats here.

like image 22
Akshat Harit Avatar answered Oct 22 '22 11:10

Akshat Harit