Solution to the sine-term problem

(Hat tip to Ethan Chen who found an error in a prior solution; it has been fixed here.)

(define PI 3.14159265357989)

(define (accumulate op id term a next b)
  (cond ((> a b) id)
        (else (op (term a) (accumulate op id term (next a) next b)))))

(define (fact n)
  (cond ((< n 2) 1)
        (else (* n (fact (- n 1))))))

Note the use of sign to make a term positive or negative.

(define (sine-term theta n)
  (let ((sign (if (even? n) - +)))
    (sign (/ (expt theta (- (* 2 n) 1))
             (fact (- (* 2 n) 1))))))

A natural question is, how do we call sine-term, which takes two inputs, when we are dealing with accumulate, whose term parameter takes only one? The answer is that one of the two inputs to sine-term is x, which has scope in the sine function. So we can use a lambda to read in the values of a in accumulate and call sine-term with x and the lambda's input (in this case, n).

Since we need 200 terms, we pass 200 into b in accumulate.

(define (sine theta)
  (accumulate +
              0
              (lambda (n) (sine-term theta n))
              1
              (lambda (n) (+ n 1))
              200))