In the sqrt
function of most languages (though here I\'m mostly interested in C and Haskell), are there any guarantees that the square root of a perfect square
Instead of doing sqrt(81.0) == 9.0
, try 9.0*9.0 == 81.0
. This will always work as long as the square is within the limits of the floating point magnitude.
Edit: I was probably unclear about what I meant by "floating point magnitude". What I mean is to keep the number within the range of integer values that can be held without precision loss, less than 2**53 for a IEEE double. I also expected that there would be a separate operation to make sure the square root was an integer.
double root = floor(sqrt(x) + 0.5); /* rounded result to nearest integer */
if (root*root == x && x < 9007199254740992.0)
/* it's a perfect square */