【发布时间】:2015-11-03 21:01:56
【问题描述】:
我正在研究一个学术问题,但我陷入了困境。
我必须实现一个函数(make-nstf f)。该函数应返回一个函数,该函数使用牛顿方法计算函数的零。
为了测试我的功能,我使用https://repl.it/BWbp/1,如果您愿意,可以将代码复制到本网站进行测试。
我的(不工作的)代码。为了给大家理解代码提供一点帮助,我写了一些cmets:
(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)
)
你能帮我找出错误吗?
问候, 超离子
【问题讨论】:
-
老实说,这是一个非常丑陋的方案。获得一个可以为您匹配括号的良好编辑环境。例如,在
myfunc中,每行有一个符号,使用 9 行可以轻松放入 2 行。如果在关闭当前行的函数的括号和关闭函数的括号之间放置一个空格,您仍然可以保持良好的可读性另一行。 -
使用更惯用的格式,你的 76 行 became 42.
标签: scheme lisp newtons-method