下面是我为牛顿方法编写的代码:
(define (newtons-method f guess n)
(define (newtons-method-h guess k)
(if(= k n)
guess
(let ((next (- guess (/ (f guess) ((der f 0.1) guess)))))
(newtons-method-h next (+ k 1)))))
(newtons-method-h guess 0))以及我用牛顿方法寻找数字平方根时编写的代码:
(define (sqrt-newt n)
(newtons-method (lambda (x) (- (* x x) n)) 1.0 40))我在想..。sqrt打电话给牛顿- 40次采访的方法吗?我相信答案是肯定的,但我在这里画了一个空白。
发布于 2013-09-21 21:09:15
只需在代码中添加一个计数器:
(define counter null) ; define a global variable
(define (newtons-method f guess n)
(define (newtons-method-h guess k)
(set! counter (add1 counter)) ; increment it at each call
(if (= k n)
guess
(let ((next (- guess (/ (f guess) ((der f 0.1) guess)))))
(newtons-method-h next (+ k 1)))))
(set! counter 0) ; initialize it before starting
(newtons-method-h guess 0))
(sqrt-newt 2) ; run the procedure
=> 1.4142135623730951
counter ; check the counter's value
=> 41如您所见,newtons-method-h过程被调用了41次--比您预期的多了一次,因为这个过程最后一次被调用时是(= k n),而那是递归结束的时候。
https://stackoverflow.com/questions/18937433
复制相似问题