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

2

5

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
Paunchy answered 16/7, 2015 at 20:28 Comment(1)
put from __future__ import division at the top of your scriptFusco
D
7

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.

Duo answered 16/7, 2015 at 20:34 Comment(2)
Note that this is only a problem in Python 2. In 3.x, / always means true division, regardless of operands.Eskew
Note that I updated the other division (in the if). Without that, it would not have worked for x=0, because it would never have gotten to the else clause, which converts it to a float. Thus it would have returned 0 for exp(0) which is incorrect.Duo
R
2
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.

Roughcast answered 16/7, 2015 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.