;; (newton f x0) ;; Starting at x0, iterate f by newton's method ;; until we are close to root. ;; ;; A "real" implementation would allow the user to ;; specify what is meant by 'close'. ;; (define newton (lambda (f x0) (let ((delta 0.00001) (y0 (f x0))) (printf "f(~s)=~s~n" x0 (f x0)) (if (< (abs y0) delta) x0 (newton f (crosses-x-at x0 y0 (estimate-slope f x0))))))) ;; (estimate-slope f x) ;; Given a function f:R->R, and a real number x, ;; find (roughly) the slope of f at x. ;; It's not particularly smart about choosing epsilon. ;; (define estimate-slope (lambda (f x) (let ((epsilon 0.0000001)) (/ (- (f (+ x epsilon)) (f x)) epsilon)))) ;; (crosses-at x0 y0 m) ;; given a point (x0,y0) and a slope m, ;; calculate where the line so determined ;; crosses the x-axis. ;; ;; This code assumes m is not zero! ;; (define crosses-x-at (lambda (x0 y0 m) (- x0 (/ y0 m)))) ;;;;;;;;;;;; ;; some test data ;; an easy linear case: ;; f(x) = x-4 ;; (define line4 (lambda (x) (- x 4))) (newton line4 17) ;; sqrt 3 ;; f(x) = x*x-3 ;; (define root3 (lambda (x) (- (* x x) 3))) (newton root3 1.0) ;; x = (tan x) ;; (define xTanx (lambda (x) (- (tan x) x))) (newton xTanx 0.0) (newton xTanx 0.1) (newton xTanx 1.0)