Search code examples
recursionschemenewtons-method

What's wrong with this Newton's Method implementation in Scheme?


Where is my flaw in the following code?

(define (newtons-method2 f guess n)
(define (newton-transform f)
 (lambda (x)
  (- x (/ (f x) ((der f 0.5) x)))))
(let ((next (newton-transform guess)))
(if (= 0 n)
    next
    (newtons-method2 (f next (- n 1))))))

The method is named "newtons-method2" because this was my second attempt at writing newton's method in scheme

My derivative function is as follows:

(define (der f h)
 (lambda (x)
 (/ (- (f(+ x h)) (f x))
    h)))

Solution

  • There are probably several problems, I found these:

    (newtons-method2 (f next (- n 1))
    ->
    (f next (- n 1))
    

    this is evaluating f with parameters next and n-1, but you want to pass all 3 as parameters:

    (newtons-method2 f next (- n 1))
    

    Be careful with parentheses, they fundamentally alter what the program does. Just because they balance, doesn't mean the program does anything meaningful.

    0.5 for delta is a huge value, and likely will cause problems when calculating the approximations. how about 0.00001?

    Learn to do proper indentation, so arguments line up below each other. Again, this is related to parentheses. It's almost impossible to read your code.

    Also, here's a nice implementation with explanation from the SICP lectures (highly recommended, brilliant): http://www.youtube.com/watch?v=erHp3r6PbJk&list=PL8FE88AA54363BC46 (from 43:14)