Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Math/sqrt precision on big integers

Why does the following Clojure code print "true"?

(please notice that the numbers differ in the last digit)

(== (Math/sqrt 10252519345963644753026N)
    (Math/sqrt 10252519345963644753025N))

Not sure whether this question is only about Clojure or if it also applies to other languages (Java's BigInteger?).

Printing them results in:

(str (Math/sqrt 10252519345963644753026N) " "
     (Math/sqrt 10252519345963644753025N))

1.01254725055E11 1.01254725055E11
like image 674
Ioanna Avatar asked Mar 10 '23 20:03

Ioanna


1 Answers

The Java Math.sqrt function

  • takes a double argument and
  • returns a doubleresult.

As various comments suggest, the conversions that this induces lose the precision to distinguish between the numbers. In fact, conversion to double does so:

(= (double 10252519345963644753026N)
   (double 10252519345963644753025N))
;true

A double has a 53 bit precision. Since 10 bits is about 3 decimal digits, this is about 16 decimal digits precision. Your numbers are 23 digits long, so the last few digits are lost in conversion.

like image 66
Thumbnail Avatar answered Mar 17 '23 10:03

Thumbnail