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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Skentuey
  • 53
  • 4

2 Answers2

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.

Jake Griffin
  • 2,014
  • 12
  • 15
  • 2
    Note that this is only a problem in Python 2. In 3.x, `/` always means true division, regardless of operands. – Kevin Jul 16 '15 at 20:36
  • 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. – Jake Griffin Jul 17 '15 at 15:36
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.

Akshat Harit
  • 814
  • 1
  • 7
  • 13