Scheme 牛顿法运行40次吗?
以下是我为牛顿方法编写的代码:Scheme 牛顿法运行40次吗?,scheme,Scheme,以下是我为牛顿方法编写的代码: (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 (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次迭代吗?我相信答案是肯定的,但我在这里画了一个空白 只需在代码中添加一个计数器即可:
(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次,比您预期的多了一次,因为该过程在(=kn)
时最后一次被调用,而那是递归结束时。向newtons-method
添加一个print语句,运行上面的代码,计算行数。