;; /home/comp212/Labs/lab4/sum.ss ;; By Dan Grossman, 96.Sep.30 ;; ;; Some examples showing innacuracies using floating-point numbers, ;; and how to try to get around them. ;; (define make-list (lambda (n s) (if (zero? n) null (cons s (make-list (sub1 n) s))))) (define a (make-list 101 5)) ; b: 1.0e16 followed by 101 5's ; c: 101 5's followed by 1.0e16 ; d: 50 5's followed by 1.0e16 followed by 51 5's ; e: 1.0e16 followed by 50 5's (define b (cons 1.0e16 a)) (define c (append a (list 1.0e16))) (define d (append (make-list 50 5) (cons 1.0e16 (make-list 51 5)))) (define e (cons 1.0e16 (make-list 50 5))) (define sum (lambda (l) (cond ((null? l) 0) (else (+ (car l) (sum (cdr l))))))) ;; better-Sum ;; take a list of numbers, and sum the elements ;; trying to avoid imprecision errors. ;; ;; (N.B. "sort" is a built-in dr.scheme function!) ;; (define better-sum (lambda (alon) (sum (sort (lambda (x y) (> (abs x) (abs y))) alon)))) ; Compare (sum b) with (better-sum b), ; and similarly for the lists c,d,e. ; Why is there a difference? (define janus (list 99 3.2e+270 -99 -2.4e+270 1234 4 -8e+269 -4)) ; (sum janus) = ?? ; (sum (reverse janus)) = ?? ; (better-sum janus) = ?? ; The correct answer = !!