Skip to content

Instantly share code, notes, and snippets.

@jeremyBanks
Created May 22, 2009 17:28
Show Gist options
  • Save jeremyBanks/116252 to your computer and use it in GitHub Desktop.
Save jeremyBanks/116252 to your computer and use it in GitHub Desktop.
[2010-01] approximating sine using an identity and knowledge that sin(x) ~= x for small values of x
#!/usr/bin/env python3.0
import sys
from fractions import Fraction
from math import sin, pi
def xsin(x, threshold=.05):
"""Sine approximation."""
if abs(x) < threshold:
return(x)
else:
return(3 * xsin(x / 3) - 4 * (xsin(x / 3) ** 3))
def main(*args):
print(" x sin xsin ∆ ")
print("------- ------ ------ ------")
for twelfths in range(-24, 24 + 1):
pis = Fraction(twelfths, 12)
x = pi * pis
xsin_x = xsin(x)
sin_x = sin(x)
diff = abs(xsin_x - sin_x)
if pis == 0:
pretty = " 0 "
elif pis.denominator == 1:
pretty = "{0.numerator:3d} π".format(pis)
else:
pretty = "{0.numerator:3d}/{0.denominator:<2d}π".format(pis)
print("{pretty} {sin_x:6.3f} {xsin_x:6.3f} {diff:6.3f}".format(**locals()))
if __name__ == "__main__": sys.exit(main(*sys.argv[1:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment