;; Some examples showing innacuracies using floating-point numbers, ;; and how to try to get around them. ;; ; make-list : natnum any -> list-of-any ; returns a list of n copies of s (define (make-list n s) (cond [(zero? n) empty] [else (cons s (make-list (sub1 n) s))])) ; example lists for addition ; list1: 1.0e16 followed by 101 5's ; list2: 101 5's followed by 1.0e16 ; list3: 50 5's followed by 1.0e16 followed by 51 5's (define list1 (cons 1.0e16 (make-list 101 5))) (define list2 (append (make-list 101 5) (list 1.0e16))) (define list3 (append (make-list 50 5) (cons 1.0e16 (make-list 51 5)))) (define janus (list 99 3.2e+270 -99 -2.4e+270 1234 4 -8e+269 -4)) ; sum : list-of-number -> number ; Returns the sum of the elements of the list (define (sum l) (cond [(empty? l) 0] [else (+ (first l) (sum (rest l)))])) ; better-sum : list-of-number -> number ; Returns the sum of the elements of the list, trying to avoid ; imprecision errors by adding small magnitude numbers first. ; ; (Note: "quicksort" is a built-in DrScheme function!) ; (define (better-sum alon) (local [(define (compare x y) (> (abs x) (abs y)))] (sum (quicksort alon compare))))