[plt-scheme] question about Scheme numbers
On May 12, 2006, at 10:21 PM, Peter Horst wrote:
> OK, so I've got (under Dr. Scheme 3.01 "Textual"):
>
> (define square
> (lambda (n)
> (* n n)))
>
> (define hypotenuse
> (lambda (adjacent opposite)
> (sqrt (+ (square adjacent) (square opposite)))))
>
> Calculating the hypotenuse of a 30-60-90 right triangle I get:
>
> > (hypo (sqrt 3) 1)
> 2.0
>
> but
>
> > (square (sqrt 3))
> 2.9999999999999996
>
> How come?
>
> Thank you!
Functions like this show how whole numbers add to other numbers that
are not quite whole:
(define (add-x-to-nearly-3 x)
(+ x 2.9999999999999996))
(map add-x-to-nearly-3
'(-1000 -100 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1.0 2.0 3 4 5 10 100
1000))
Results could depend a little on the computer:
(-997.0
-97.0
-7.0
-6.0
-5.0
-4.0
-3.0000000000000004
-2.0000000000000004
-1.0000000000000004
-4.440892098500626e-16
0.9999999999999996
1.9999999999999996
2.9999999999999996
3.9999999999999996
5.0
6.0
7.0
8.0
13.0
103.0
1003.0)
The effect is only noticeable on results near zero (for reasons that
others have given.)
rac