Python script to compute Taylor expansion (cos(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 (cos(x)) | |
""" | |
import math | |
import sys | |
import traceback | |
class TaylorExpansionCos: | |
EPS = 1e-08 # Precision | |
PI = 3.1415926535 # Pi | |
def compute(self): | |
""" Computation of Taylor expansion """ | |
try: | |
rad = self.PI / 180 | |
print(" x mycos(x) cos(x)") | |
for x in range(0, 181, 10): | |
cos, cos_2 = math.cos(x * rad), self.__cos(x * rad) | |
print("{:5.1f}{:14.6f}{:14.6f}".format(x, cos_2, cos)) | |
except Exception as e: | |
raise | |
def __cos(self, x): | |
""" Computation of cos(x) | |
:param float x | |
:return float exp | |
""" | |
try: | |
d = s = e = 1.0 | |
x %= 2 * self.PI | |
for k in range(1, 201, 2): | |
d = s | |
e *= -x * x / (k * (k + 1)) | |
s += e | |
if abs(s - d) / abs(d) < self.EPS: | |
return s | |
return 9999.0 | |
except Exception as e: | |
raise | |
if __name__ == '__main__': | |
try: | |
obj = TaylorExpansionCos() | |
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