Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active February 26, 2018 01:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save komasaru/893a8910b9604ca14eeb0ce4b1853aca to your computer and use it in GitHub Desktop.
Python script to compute Taylor expansion (cos(x)).
#! /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