SICP exercise 1.40
From Drewiki
Problem
Define a procedure cubic that can be used together with the newtons-method procedure from the text in expressions of the form (newtons-method (cubic a b c) 1) to approximate zeros of the cubic x3 + ax2 + bx + c.
Solution
Here's cubic:
(define (cube x) (* x x x)) (define (square x) (* x x)) (define (cubic a b c) (lambda (x) (+ (cube x) (* a (square x)) (* b x) c)))
And here's newtons-method and friends from the text:
(define tolerance 0.00001) (define (fixed-point f first-guess) (define (close-enough? v1 v2) (< (abs (- v1 v2)) tolerance)) (define (try guess) (let ((next (f guess))) (if (close-enough? guess next) next (try next)))) (try first-guess)) (define dx 0.00001) (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define (newton-transform g) (lambda (x) (- x (/ (g x) ((deriv g) x))))) (define (newtons-method g guess) (fixed-point (newton-transform g) guess))
Tests performed using Chicken Scheme 3.1 on a MacBook Pro running Mac OS X 10.5.
(newtons-method (cubic 1 1 1) 1)
Output:
-0.99999999999978
(newtons-method (cubic 0 0 0) 1)
Output:
2.65319902917972e-05
(newtons-method (cubic 0 0 -1) 1)
Output:
1.0
(newtons-method (cubic 2 1 2) 1)
Output:
-1.99999999998065

