Scheme streams with Taylor series

1.1k views Asked by At

I've been doing some homework, wrote some code and can't actually find the reason why it doesn't work. The main idea of this part of the work is to make a stream that will give me elements of Taylor series of cosine function for a given X (angle i guess). anyways here is my code, I'd be happy if some one could point me to the reasons it doesn't work :)

(define (force exp) exp)
(define (s-car s) (car s))
(define (s-cdr s) (force (cdr s)))

; returns n elements of stream s as a list
(define (stream->list s n)
  (if (= n 0) 
      '()
      (cons (s-car s) (stream->list (s-cdr s) (- n 1)))))

; returns the n-th element of stream s
(define stream-ref (lambda (s n)
                     (if (= n 1)
                         (s-car s)
                         (stream-ref (s-cdr s) (- n 1)))))

; well, the name kinda gives it away :) make factorial n!
(define (factorial x)
        (cond ((= x 0) 1)
              ((= x 1) 1)
              (else (* x (factorial (- x 1))))))

; this function is actually the equation for the 
; n-th element of Taylor series of cosine
(define (tylorElementCosine x)
  (lambda (n)
     (* (/ (expt -1 n) (factorial (* 2 n))) (expt x (* 2 n)))))

; here i try to make a stream of those Taylor series elements of cosine
(define (cosineStream x)
  (define (iter n)
    (cons ((tylorElementCosine x) n)
          (lambda() ((tylorElementCosine x) (+ n 1)))))
  (iter 0))

; this definition should bind cosine
; to the stream of taylor series for cosine 10
(define cosine (cosineStream 10)) 
(stream->list cosine 10) 
; this should printi on screen the list of first 10 elements of the series

However, this doesn't work, and I don't know why.

I'm using Dr.Scheme 4.2.5 with the language set to "Essentials of Programming Languages 3rd ed".

1

There are 1 answers

2
Grizzly On BEST ANSWER

Since I was feeling nice (and nostalgic about scheme) I actually waded through your code to finde the mistakes. From what I can see there are 2 problems which keeps the code from running as it should:

If I understand your code correctly (force exp) should evaluate exp, however you directly return it (unevaluated). So it probably should be defined as (define (force exp) (exp))

The second problem is in your lambda: (lambda() ((tylorElementCosine x) (+ n 1)) ) will evaluate to the next element of the taylor series, while it should evaluate to a stream. You probably want something like this: (lambda() (iter (+ n 1)) )

I haven't checked if the output is correct, but with those modifications it does at least run. So if there are any more problems with the code the should be in the formula used.

However I'd suggest that next time you want help with your homework you at least tell us where exactly the problem manifests and what you tried already (the community does frown on "here is some code, please fix it for me" kind of questions).