File: rational.lsp

package info (click to toggle)
xlispstat 3.52.14-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 7,560 kB
  • ctags: 12,676
  • sloc: ansic: 91,357; lisp: 21,759; sh: 1,525; makefile: 521; csh: 1
file content (23 lines) | stat: -rw-r--r-- 893 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(in-package :xlisp)
(export 'rationalize)
(defun rationalize (val)	; hopefully readable conversion
       (unless (typep val 'flonum)
	       (if (typep val 'rational)
		   (return-from rationalize val)
		   (error "~s is invalid type" val)))
       (let ((fraction (abs (rem val 1.0))))
	    (if (zerop fraction) 
		(round val)
		(let ((limit (expt 10 (- (+ 7 (truncate (log fraction 10)))
					  (max 0 (truncate (log (abs val) 10))))))
		      divisor)
		     (cond ((>= limit 10000)	; allow primes 3 3 7 11 13
			    (setq limit (* 9009 (/ limit 10000))))
			   ((>= limit 1000)	; allow primes 3 3 7 11
			    (setq limit (* 693 (/ limit 1000))))
			   ((>= limit 100)	; allow primes 3 3 7
			    (setq limit (* 63 (/ limit 100)))))
		     (setq divisor (round (/ limit fraction)))
		      (if (floatp divisor) 
			  (round val)	; Doesn't fit
			  (/ (round (* val divisor)) divisor))))))