File: ratize.scm

package info (click to toggle)
slib 2d2-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 2,468 kB
  • ctags: 1,726
  • sloc: lisp: 20,736; makefile: 333; sh: 158
file content (17 lines) | stat: -rw-r--r-- 668 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
;;;; "ratize.scm" Find simplest number ratios

(define (find-ratio-between x y)
  (define (sr x y)
    (let ((fx (inexact->exact (floor x))) (fy (inexact->exact (floor y))))
      (cond ((>= fx x) (list fx 1))
	    ((= fx fy) (let ((rat (sr (/ (- y fy)) (/ (- x fx)))))
			 (list (+ (cadr rat) (* fx (car rat))) (car rat))))
	    (else (list (+ 1 fx) 1)))))
  (cond ((< y x) (find-ratio-between y x))
	((>= x y) (list x 1))
	((positive? x) (sr x y))
	((negative? y) (let ((rat (sr (- y) (- x))))
			 (list (- (car rat)) (cadr rat))))
	(else '(0 1))))
(define (find-ratio x e) (find-ratio-between (- x e) (+ x e)))
(define (rationalize x e) (apply / (find-ratio x e)))