exercise-1.40-polynome-newton-method.rkt 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #lang racket
  2. (define (Mb-to-B n) (* n 1024 1024))
  3. (define MAX-BYTES (Mb-to-B 64))
  4. (custodian-limit-memory (current-custodian) MAX-BYTES)
  5. (define (derivative g)
  6. (let
  7. ((h 0.000001))
  8. (lambda (x)
  9. (/
  10. (- (g (+ x h)) (g x))
  11. h))))
  12. (define tolerance 0.000000000001)
  13. (define (fixed-point f guess)
  14. (define (close-enough? value1 value2)
  15. (< (abs (- value1 value2)) tolerance))
  16. (define (try current-guess)
  17. (let
  18. ((next (f current-guess)))
  19. (if
  20. (close-enough? current-guess next)
  21. next
  22. (try next))))
  23. (try guess))
  24. ;; to calculate g(x) = 0
  25. ;; newton transformation
  26. (define (newton-transform g)
  27. (lambda (x)
  28. (- x (/ (g x) ((derivative g) x)))))
  29. ;; newton method
  30. (define (newton-method g guess)
  31. ; the g(x) = 0 (a zero of g) point can be calculated
  32. ; by determining the fixed point of the
  33. ; newton transformed function g, according to the book
  34. (fixed-point (newton-transform g) guess))
  35. (define (cubic a b c)
  36. (lambda (x)
  37. (+ (* x x x) (* a x x) (* b x) c)))
  38. (time (newton-method
  39. (cubic 1 3 -2)
  40. -1.8))