When I try the following in racket:
(* 1.1 1.1)
why does it return
1.2100000000000002
instead of
1.21
while
(* 1.2 1.2) ; is 1.44, as expected
and the following returns false:
(= (* 1.1 1.1) 1.21); #f
Oh look, this compares correctly!
> (= (* #e1.1 #e1.1) #e1.21)
#t
(Racket has this really nice feature that #e1.1
is actually read in as exactly 1.1. Other Scheme implementations do not necessarily work that way, and may actually read in #e1.1
as floating-point first and then convert to exact.)
Anyway, to elaborate on everybody else's point, without an exactness specifier, Scheme treats a number literal with a dot in it as inexact† (that is, 1.1
and #i1.1
read in as the same thing). And with inexact numbers, you cannot really expect sane results when doing "exact" comparisons (such as =
).
† R7RS, section 6.2.5: "If the written representation of a number has no exactness prefix, the constant is inexact if it contains a decimal point or an exponent. Otherwise, it is exact."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With