Calculating Sines
January 12, 2010
Taylor Series
Just as we did previously when calculating logarithms, we start our solution for calculating sines by defining epsilon as the desired accuracy of the final result; we also give a definition for π:
(define epsilon 1e-7)
(define pi 3.141592654)
Since each term of the Taylor series contains a factorial in its denominator, we’ll need a fast way to compute factorials. The following iterative procedure comes from section 1.2.1 of Structure and Interpretation of Computer Programs (SICP):
(define (factorial n)
(fact-iter 1 1 n))
(define (fact-iter product counter max-count)
(if (> counter max-count)
product
(fact-iter (* counter product)
(+ counter 1)
max-count)))
The following procedure will compute the nth term of the Taylor sine series given n and the angle in radians:
(define (term n radians)
(* (/ (expt radians (+ (* 2 n) 1))
(factorial (+ (* 2 n) 1)))
(expt -1 n)))
Since the sine function is periodic, computation time for large angles can be greatly improved by reducing the angle to the range [-π, π] before computing the Taylor series.
(define (reduce x)
(- x (* (round (/ x (* 2 pi))) 2 pi)))
Finally, we can define a procedure that iteratively adds terms of the Taylor series to a sum until the desired precision is reached.
(define (good-enough? current next)
(< (abs (- current next)) epsilon))
(define (sine-iter radians n current next)
(if (good-enough? current next)
next
(sine-iter radians (+ n 1) next (+ next
(term (+ n 1) radians)))))
(define (taylor-sine radians)
(sine-iter (reduce radians) 0 0 (term 0 (reduce radians))))
The sine-iter
procedure keeps track of both the current and the next sum of the terms of the Taylor series, only halting execution when the good-enough?
procedure determines that the difference between the two is smaller than the epsilon value we defined earlier. The taylor-sine
procedure simply reduced the input angle and calls the iterative procedure with initial values.
Here are a few sample calculations:
> (taylor-sine 1)
0.841470984648068
> (taylor-sine (/ pi 2))
1.0000000006627803
> (taylor-sine 10)
-0.5440211113737637
Recursive formula
One solution that uses the approximation sin x ≈ x, and the triple-angle formula can be found in SICP section 1.2.3:
(define (cube x) (* x x x))
(define (p x) (- (* 3 x) (* 4 (cube x))))
(define (sine angle)
(if (not (> (abs angle) 0.1))
angle
(p (sine (/ angle 3.0)))))
The only thing we need to change is the criteria for considering an angle “sufficiently small.” If we change 0.1 in the comparison on the 4th line of the code above to the epsilon
value we defined earlier, we gain the needed precision.
(define (cube x) (* x x x))
(define (p x) (- (* 3 x) (* 4 (cube x))))
(define (sine angle)
(if (not (> (abs angle) epsilon))
angle
(p (sine (/ angle 3.0)))))
Once again, here are a few sample calculations:
> (sine 1)
0.8414709848078971
> (sine (/ pi 2))
1.0
> (sine 10)
-0.5440211108893757
You can run the program at http://programmingpraxis.codepad.org/uyaebBRj.
Here is my version of
taylor-sine
, which keeps the numerator and denominator separately and calculates each by updating the previous value rather than recalculating each from scratch at each iteration.(define (taylor-sine x)
(let loop ((n x) (d 1) (k 1) (s x) (t -1))
(let* ((next-n (* n x x))
(next-d (* d (+ k 1) (+ k 2)))
(next (* t (/ next-n next-d))))
(if (< (abs next) epsilon)
(exact->inexact (+ s next))
(loop next-n next-d(+ k 2) (+ s next) (* t -1))))))
I also eschew the range-reduction optimization, as http://dotancohen.com/eng/taylor-sine.php shows little improvement from the optimization.
my solution using c
programmingpraxis,
I’d say that the page you linked to gives a strong argument in favor of range reduction. It shows that when you reduce the range, only very few terms of the Taylor series are required to accurately approximate sine(x), even for large x. Your optimization of keeping the numerator and (particularly) the denominator, and updating each instead of recalculating on each iteration helps a lot. However, as x grows, even just updating the factorial in the denominator can take quite a bit of time. For example, without using range reduction it takes my machine about 25 seconds to compute (taylor-sine 1000). With range reduction I get the answer immediately, with no significant loss of accuracy.
[…] Praxis – Calculating Sines By Remco Niemeijer In today’s Programming Praxis exercise we have to implement two ways of calculating sines. Let’s get […]
My Haskell solution (see http://bonsaicode.wordpress.com/2010/01/12/programming-praxis-calculating-sines/ for a version with comments):
Bill the Lizard: You are correct. My mistake.
My purely iterative solution, with range reduction, in 27 lines: http://codepad.org/HgaJbSbh
Just a nitpicking. Shouldn’t it be lim ( sin(x) / x ) = 1 when x -> 0
My first attempt to programming in haskell:
sin' :: (Double -> Double) -> Double -> Double
sin' f x = reduce1 f (x - fromIntegral(truncate(x / (2*pi)))*(2*pi))
reduce1 :: (Double -> Double) -> Double -> Double
reduce1 f x
| x Double) -> Double -> Double
reduce2 f x
| x <= pi/2 = f x
| x <= pi = f (pi - x)
| x Double
taylor x = let (_,_,_,r) = foldl sumOdd (1,1,-1,0) [1..20]
where sumOdd (n,d,s,p) el
| even el = (n*x,d*fromIntegral el,-s,p-s*n/d)
| otherwise = (n*x,d*fromIntegral el,s,p)
in r
sinIter :: Double -> Double
sinIter x
| x < 1e-7 = x
| otherwise = 3*sinIter(x/3) - 4*sinIter(x/3)**3
And is amazingly working:
*Main> sin’ taylor (pi*0.25)
0.7071067811865475
*Main> sin’ sinIter (pi*0.25)
0.7071067811865475
*Main> sin (pi*0.25)
0.7071067811865475
And it took me only 10 times more time that it would have taken me in C …
Manish: Fixed. My fault, not Bill’s.
A version written in F#.
let epsilon = 1e-7
let pi = 3.141592654
let sin (x:float) =
let rec series sum f d v k2 =
let next = f * d / float v
if abs(next) < epsilon then
sum + next
else
series (sum + next) (-f) (d * x * x) (v * (k2 + 1) * (k2 + 2)) (k2 + 2)
series 0.0 1.0 1.0 1 1
let rec sin' x =
if abs(x) float
val sin’ : float -> float
> sin 1.0;;
val it : float = 0.8414709846
> sin’ 1.0;;
val it : float = 0.8414709848
the comment section ate my code …
Here is a version written in F#.
http://pastie.org/777280
[…] dabbling with haskell in the recent days. My first semi-serious attempt was inspired by a prompt at programming praxis. The code I concocted is as follows (I guess it would ashame any serious haskell programmer, if you […]
Python:
Version in Factor. Interesting that the Taylor series is minimally accurate to the given precision (1e-7), but the recursive version is much more precise than our minimum of 1e-7. Probably the case as for values that small sin x ~= x.
Session:
My
sin_taylor()
works quite well, but my recursivesin_limit
runs into numerical trouble if epsilon is too small…like Matías Giovannini, i went for the purely iterative implementations
oops, usage says to provide input in degrees, but that should be radians