2015-11-03 53 views
-1

我正在研究一个学术问题,我被卡住了。Lisp(Scheme)Newton方法

我要实现的功能(使-NSTF F)。该函数应该返回一个函数,该函数通过使用牛顿方法来计算函数的零。

为了测试我的功能我用https://repl.it/BWbp/1您可以将代码复制到这个网站,如果你想测试它。

我(不工作)的代码。我写了一些评论,以便给大家一点帮助理解代码:

(define (abs x) 
    (if (< x 0) (- x) x) 
) 

;defines a function dif which returns another function (derivative) 
(define (dif fkt k) 
    (lambda (x) 
     (/ 
      (- 
       (fkt (+ x k)) 
       (fkt (- x k)) 
      ) 
      (* 2 k) 
     ) 
    ) 
) 

;Calculates next x for newton method 
(define (nextx f x) 
    (- 
     x 
     (/ 
      (f x) 
      ((dif f 1) x) 
     ) 
    ) 
) 

;Should return a function which does the newton method with function f 
(define (make-nstf f) 
    (lambda(guess) 
     ;Function checks whether the guess is good enough or not 
     ;good enoug if guess - next guess < 0.0001 ist 
     (define (good-enough? guess) 
      (< 
       (abs 
        (- 
         guess 
         (nextx f guess) 
        ) 
       ) 
      ) 
      0.0001 
     ) 
     ;calculates next guess 
     (define (improve guess) 
      (nextx f guess) 
     ) 
     ;checks whether guess is good enough and if not improve guess and try again 
     (define (sqrt-iter guess) 
      (if (good-enough? guess) 
       guess 
       (sqrt-iter (improve guess)) 
      ) 
     ) 
     ;Start with guess 
     (sqrt-iter guess) 
    ) 
) 

;defines a function: (3*x*x)-2 
(define (myfunc x) 
    (- 
     (* 
      3 
      x 
      x 
     ) 
     2 
    ) 
) 

;defines a function which calls mak-nstf with my func. 
(define nstf 
    (make-nstf myfunc) 
) 

能否请你帮我找到了这个错误?

问候, 海波

+1

这是非常丑陋的方案是诚实的。获得一个可以匹配括号的良好编辑环境。例如在'myfunc'中,每行有一个符号,每行使用9行代码,可轻松放入2.如果在当前行中关闭函数的关系和关闭函数的关系之间放置一个空格,其他线路。 – WorBlux

+0

使用更多的惯用格式,你的76行[成为42](https://repl.it/BWrP)。 – molbdnilo

回答

0

你有good-enough?放错了地方接近括号(那些偷偷摸摸的括号...)

(define (good-enough? guess) 
    (< 
     (abs 
      (- 
       guess 
       (nextx f guess) 
      ) 
     ) 
    ) 
    0.0001 ;this should be moved up a line 
)