math - Calculating exp(x) with the use of recursion in Python -
this question has answer here:
- python division 11 answers
i'm attempting calculate e^x using recursion, e^x = e^(x/2)*e^(x/2), , third order maclaurin expansion e^x , script keeps returning 1. i'm not looking higher accuracy solution, understand script goes wrong : )
my thought enough iterations should end (1+x/n+(x/n)^2/2)^n when function value goes below limit.
def exp(x): if abs(x)<0.0001: return 1+x+x**2/2 else: y=exp(x/2) return y*y
try instead (note 2.0
in 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 failing because if pass integer in x
, 1
, x / 2
integer division (in python 2.x), result in 0
instead of 0.5
. using x / 2.0
, forces python use float division.
Comments
Post a Comment