How would I go about create this function

90 views Asked by At

How would I create an approximate cos function.

What I have so far.

 (define k 0) 
(define (approx-cos x n) 
  (cond
    [(> 0 n) 0]
    [else (*  (/ (expt -1 k) (factorial (* 2 k))) (expt x (* 2 k)))]))





1

There are 1 answers

4
Óscar López On BEST ANSWER

Your solution requires a lot of work before it meets the expectations. For starters, your parameters are switched: the first one is the number you want to calculate and the second one is the number of iterations...

Which leads me to the major problem in your solution, you're not iterating at all! You're supposed to call approx-cos at some point, or some helper procedure to do the looping (as I did).

Last but not least, you're not correctly implementing the formula. Where's the -1 part, for instance? Or where are you multiplying by x^2k? I'm afraid a complete rewrite is in order:

; main procedure
(define (approx-cos x n)
  ; call helper procedure
  (loop 0 0 x n))

; define a helper procedure
(define (loop acc k x n)
  ; loop with k from 0 to n, accumulating result
  (cond [(> k n) acc] ; return accumulator
        [else
         (loop (+ acc ; update accumulator
                  (* (/ (expt -1.0 k) ; implement the formula
                        (factorial (* 2.0 k)))
                     (expt x (* 2.0 k))))
               (add1 k) ; increment iteration variable
               x n)]))

This will pass all the check expects:

(approx-cos 0 0)
=> 1
(approx-cos (/ pi 2) 0)
=> 1
(approx-cos 0 10)
=> 1
(approx-cos pi 10)
=> -0.9999999999243502
(approx-cos (* 3 (/ pi 2)) 9)
=> -1.1432910825361444e-05
(approx-cos 10 100)
=> -0.8390715290756897

Some final thoughts: your implementation of factorial is very slow, if you plan to do a larger number of iterations, your factorial will freeze the execution at some point.