Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active April 30, 2016 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louisswarren/238361daebf464117d6d7f1cbdbb933a to your computer and use it in GitHub Desktop.
Save louisswarren/238361daebf464117d6d7f1cbdbb933a to your computer and use it in GitHub Desktop.
Test Taylor series approximations to sin
from math import factorial, pi, sin
def max_diff(f, g, v):
return max(abs(f(x) - g(x)) for x in v)
def zigrange(x, s=1.0):
yield 0
for y in range(1, int(x / s + 0.5) + 1):
yield y * s;
yield -y * s;
# Test up to x**9 / (9!)
max_terms = 5
odd = lambda n: 2 * n + 1
terms = [lambda x, i=i:
(-1)**i * x**(odd(i)) / factorial(odd(i)) for i in range(max_terms)]
apprs = [lambda x, n=n:
sum(f(x) for f in terms[:n + 1]) for n in range(max_terms)]
for n, appr in enumerate(apprs):
error = max_diff(sin, appr, zigrange(pi / 2, 1e-3))
print("With {} terms, the maximum error is {}".format(n + 1, error))
# Results:
# With 1 terms, the maximum error is 0.5710000207413871
# With 2 terms, the maximum error is 0.07521538109194614
# With 3 terms, the maximum error is 0.004528924235860932
# With 4 terms, the maximum error is 0.00015708088474730708
# With 5 terms, the maximum error is 3.5476258620770196e-06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment