Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to compute Taylor expansion (exp(x)).
#! /usr/local/bin/python3.6
"""
Taylor expansion (exp(x))
"""
import math
import sys
import traceback
class TaylorExpansion:
EPS = 1e-08 # Precision
def compute(self):
""" Computation of Taylor expansion """
try:
print(" x myexp(x) exp(x)")
for x in range(-50, 51, 10):
exp, exp_2 = math.exp(x), self.__calc_exp(x)
print("{:5.1f}{:14g}{:14g}".format(x, exp_2, exp))
except Exception as e:
raise
def __calc_exp(self, x):
""" Computation of exp(x)
:param float x
:return float exp
"""
try:
d = s = e = 1.0
for k in range(1, 201):
d = s
e = e * abs(x) / k
s += e
if abs(s - d) / abs(d) < self.EPS:
return s if x > 0 else 1.0 / s
return 0.0
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = TaylorExpansion()
obj.compute()
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.