sqrt, perfect squares and floating point errors

后端 未结 4 1041
逝去的感伤
逝去的感伤 2020-12-18 00:45

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

4条回答
  •  抹茶落季
    2020-12-18 00:54

    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 */
    

提交回复
热议问题