I verified experimentally that in Java the equality
Math.sqrt(x*x) = x
holds for all long x
such that x*x
doesn't overflow. Here, Java long
is a $64$ bit signed type and double
is a IEEE binary floating point type with at least $53$ bits mantissa and sufficiently long exponent.
Mathematically, there are two imprecise functions involved:
- Conversion from
long
todouble
which loses precision due to the mantissa being only $53$ bits where $63$ bits would be needed. This operation is guaranteed to return the closest representable result. - Computing square root, which is also guaranteed to return the closest representable result.
Mathematically, this can be expressed like
$$ \mathop\forall_{x \in {\mathbb N} \atop x \le 3037000499} \mathrm{round}\left(\sqrt{\mathrm{round}(x^2)}\right) = x $$
where $\mathrm{round}$ is the rounding function from $\mathbb R$ into the set of all numbers representable as double
.
I'm looking for a proof since no experiment can assure it works across all machines.