Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ sqrt function precision for full squares

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 ?

like image 238
Rafi Kamal Avatar asked Nov 22 '13 04:11

Rafi Kamal


1 Answers

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.

like image 181
Joe Z Avatar answered Oct 15 '22 12:10

Joe Z