sine.py


Below is the syntax highlighted version of sine.py from §1.3 Conditionals and Loops.


#-----------------------------------------------------------------------
# sine.py
#-----------------------------------------------------------------------

import stdio
import sys
import math

# Accept float x as a command-line argument. Compute sin(x) using the
# Taylor expansion sin x = x - x^3/3! + x^5/5! - x^7/7! + ...
# Write the result to standard output.

x = float(sys.argv[1])

# Convert x to an angle between -2 PI and 2 PI using the identity
# sin(x) = sin(x + 2 PI)
twoPi = 2 * math.pi
while x > twoPi:
    x -= twoPi
while x < twoPi:
    x += twoPi

# Alternative:
# x = x % (2 * math.pi)  # Yes, % works with floats!

# Compute the Taylor series approximation.
term = 1.0      # ith term = x^i / i!
total = 0.0     # sum of first i terms in taylor series

i = 1
while term != 0.0:
    term *= (x / float(i))
    if i % 4 == 1:
        total += term
    if i % 4 == 3:
        total -= term
    i += 1

stdio.writeln(total)

#-----------------------------------------------------------------------

# python sine.py 0 
# 4.372542542582082e-15

# python sine.py 1.5707963267948966
# 1.0000000000000304

# python sine.py 3.141592653589793
# 6.830582986146365e-14


Copyright © 2000–2015, Robert Sedgewick, Kevin Wayne, and Robert Dondero.
Last updated: Fri Oct 20 20:45:16 EDT 2017.