newton-method-fixed-point.rkt 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 (square x) (* x x))
  6. (define (derivative g)
  7. (let
  8. ((h 0.000001))
  9. (lambda (x)
  10. (/
  11. (- (g (+ x h)) (g x))
  12. h))))
  13. (define tolerance 0.0000000001)
  14. (define (fixed-point f guess)
  15. (define (close-enough? value1 value2)
  16. (< (abs (- value1 value2)) tolerance))
  17. (define (try current-guess)
  18. (display current-guess) (newline)
  19. (let
  20. ((next (f current-guess)))
  21. (if
  22. (close-enough? current-guess next)
  23. next
  24. (try next))))
  25. (try guess))
  26. ;; to calculate g(x) = 0
  27. ;; newton transformation
  28. (define (newton-transform g)
  29. (lambda (x)
  30. (- x (/ (g x) ((derivative g) x)))))
  31. ;; newton method
  32. (define (newton-method g guess)
  33. ; the g(x) = 0 (a zero of g) point can be calculated
  34. ; by determining the fixed point of the
  35. ; newton transformed function g, according to the book
  36. (fixed-point (newton-transform g) guess))
  37. (newton-method
  38. (lambda (x)
  39. (- (square x) 2))
  40. 1.0)
  41. ; if we shift a quadratic curve downwards, by substracting an n from it
  42. ; it will intersect with the x axis at the point, where the square root
  43. ; of n is
  44. ; this idea is used in the following way of calculating the square root
  45. ; for a parameter of 2
  46. ; it is the same as the call above this comment,
  47. ; where the 2 is hard coded
  48. (define (sqrt n)
  49. (newton-method
  50. (lambda (x)
  51. (- (square x) n))
  52. 1.0))
  53. (sqrt 2)