Search code examples
pythonmathrecursionexp

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


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

Solution

  • 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.