Squaring a number producing a value twice the number of bits in the original values. Hence if x is too large then some bits are lost in x^2
and x
cannot be fully recovered from y
[Edit: it's still possible to get x from y with proper rounding]. In case of IEEE-754 double precision then if x
has more than 26 bits in the significand part then the result of y
will be truncated. That's the simplest case.
If x
has few significand bits but very large or very small exponent then x^2
might be too large for double precision and will become inf
or denormal number, in which case there's no way to recover x
.
If x
is not too large or too small then sqrt(y)
would be equal to x
because IEEE-754 standard requires +
, -
, *
, /
and sqrt
to be properly rounded.
#include <iostream>
#include <ios>
#include <iomanip>
#include <cmath>
using std::fixed;
using std::hexfloat;
using std::cout;
int main() {
double x = 1.25e155;
double y = x*x;
cout << hexfloat << "x = " << x << ", y = " << y << ", sqrt(y) = " << sqrt(y) << '\n';
x = 1.25e-155;
y = x*x;
cout << hexfloat << "x = " << x << ", y = " << y << ", sqrt(y) = " << sqrt(y) << '\n';
return 0;
}