Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why (* 1.1 1.1) is 1.2100000000000002 in racket? [duplicate]

Tags:

scheme

racket

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

Edit

and the following returns false:

(= (* 1.1 1.1) 1.21); #f
like image 215
muyueh Avatar asked Jan 13 '23 13:01

muyueh


1 Answers

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."

like image 168
Chris Jester-Young Avatar answered Jan 17 '23 17:01

Chris Jester-Young