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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With