lize.scm 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. ; Part of Scheme 48 1.9. See file COPYING for notices and license.
  2. ; Authors: Alan Bawden
  3. ; Simplest rational within an interval. Copied from IEEE P1178/D4 nimpl.tex.
  4. (define (rationalize x e)
  5. (let ((e (abs e)))
  6. (simplest-rational (- x e) (+ x e))))
  7. (define (simplest-rational x y)
  8. (define (simplest-rational-internal x y)
  9. ;; assumes 0 < X < Y
  10. (let ((fx (floor x))
  11. (fy (floor y)))
  12. (cond ((not (< fx x))
  13. fx)
  14. ((= fx fy)
  15. (+ fx
  16. (/ 1 (simplest-rational-internal
  17. (/ 1 (- y fy))
  18. (/ 1 (- x fx))))))
  19. (else
  20. (+ 1 fx)))))
  21. ;; Do some juggling to satisfy preconditions of simplest-rational-internal.
  22. (cond ((not (< x y))
  23. (if (rational? x)
  24. x
  25. (assertion-violation 'rationalize "(rationalize <irrational> 0)" x)))
  26. ((positive? x)
  27. (simplest-rational-internal x y))
  28. ((negative? y)
  29. (- 0 (simplest-rational-internal (- 0 y) (- 0 x))))
  30. (else
  31. (if (and (exact? x) (exact? y))
  32. 0
  33. (exact->inexact 0)))))