C++ sqrt function precision for full squares

£可爱£侵袭症+ 提交于 2019-12-19 02:20:31

问题


Let, x is an integer and y = x * x.

Then is it guaranteed that sqrt(y) == x?

For example, can I be sure that sqrt(25) or sqrt(25.0) will return 5.0, not 5.0000000003 or 4.999999998 ?


回答1:


No, you cannot be guaranteed. For integers and their squares that fit in the dynamic range of the floating point type's mantissa (2^53 for a typical C/C++ double), you're likely to be OK, but not necessarily guaranteed.

You should avoid equals comparisons between floating point values and exact values, especially exact integer values. Floating point rounding modes and other such things can really get in your way.

You either want to use a "comparison range" to accept an "approximately equal" result, or recast your algorithm in terms of integers. There are multiple StackOverflow questions covering floating point equality comparisons. I suggest you search for them and read up.

For a certain class of problem, I wrote up an alternate solution here: Find n-th root of all numbers within an interval

That solution took a different approach than relying on tricky floating point arithmetic.




回答2:


An implementation conforming to the IEEE-754 standard on allowed errors for basic operations (of which sqrt is an example) requires that values be correctly rounded.
This means that the error will less than 1/2 ULP (unit in the last place) or basically as close as possible to the actual answer.

To answer your question, if the actual answer is exactly representable by a double then you will get the exact answer.

Note: this is not guaranteed by the C++ standard but by the IEEE-754 standard, which probably isn't an issue for most people.

Ultimately, a simple test should be sufficient for your purposes:

    for(int i = 0; i < (int)std::sqrt(std::numeric_limits<int>::max()); i++)
    {
        assert((int)(double)i == i);//Ensure exactly representable, because why not
        assert(std::sqrt((double)i*i) == i);
    }

If this passes, I don't see any reason to worry.




回答3:


You should be able to brute force search all the values up to 2^26 quite easily, but I believe the answer is yes. After that number, no.

The digit-by-digit textbook algorithm for square root finishes with remainder == 0, giving exact results. Then again if a floating point library claims ieee-754 compliancy, it'll give this value by any other means too.



来源:https://stackoverflow.com/questions/20137105/c-sqrt-function-precision-for-full-squares

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!