【问题标题】:Scheme streams with Taylor series泰勒级数的方案流
【发布时间】:2012-02-07 03:15:35
【问题描述】:

我一直在做一些功课,编写了一些代码,但实际上找不到它不起作用的原因。这部分工作的主要思想是制作一个流,它将为给定 X(我猜是角度)提供泰勒级数余弦函数的元素。无论如何,这是我的代码,如果有人能指出它不起作用的原因,我会很高兴:)

(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

但是,这不起作用,我不知道为什么。

我正在使用 Dr.Scheme 4.2.5,语言设置为“Essentials of Programming Languages 3rd ed”。

【问题讨论】:

  • 您认为“它不起作用”是准确的故障描述?它究竟是如何不起作用的?你试过调试吗?
  • 是的,我没有,一旦代码存在并且90%的代码像魅力一样工作并且只存在2个逻辑错误......没有dis mate :)

标签: stream scheme taylor-series


【解决方案1】:

因为我感觉很好(并且对方案感到怀念),我实际上是在你的代码中寻找错误。据我所知,有两个问题使代码无法正常运行:

如果我正确理解您的代码(force exp) 应该评估exp,但是您直接返回它(未评估)。所以大概应该定义为(define (force exp) (exp))

第二个问题在于您的 lambda:(lambda() ((tylorElementCosine x) (+ n 1)) ) 将评估为 taylor 系列的下一个元素,而它应该评估为流。你可能想要这样的东西:(lambda() (iter (+ n 1)) )

我没有检查输出是否正确,但经过这些修改,它至少可以运行。因此,如果代码有任何问题,应该在使用的公式中。

不过,我建议您下次在作业方面需要帮助时,至少告诉我们问题的具体表现在哪里以及您已经尝试过什么(社区确实对“这里有一些代码,请帮我修复它”皱眉头)类型的问题)。

【讨论】:

  • 谢谢,这就像一个魅力......我对这两个错误都不好:) 抱歉,我第一次在这里寻求帮助......我很少在编程方面寻求帮助因为我在我的大学里教 C 作为导师......非常感谢!实际上,我在尝试修复我唯一的错误是 lambda 表达式时犯了第一个错误......
  • @nocgod:问题风格没问题,我只需要提一下,因为那些基本上说我有问题的问题,请帮助我通常不是那么受欢迎(出于显而易见的原因,它听起来请做我所有的工作)。所以将来你可以更好地提出你的问题;)
猜你喜欢
  • 2014-04-03
  • 1970-01-01
  • 2013-01-10
  • 2017-12-02
  • 2014-02-23
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 2011-11-04
相关资源
最近更新 更多