Last active
March 17, 2021 17:05
-
-
Save komasaru/40db0411618710dc4ab5f1b7747717b3 to your computer and use it in GitHub Desktop.
Python script to compute Taylor expansion (exp(x)).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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