Say you wanted to calculate the floored square root of a number in C++, and you do: (int)sqrtl(x)
.
Or you wanted to calculate the floored base b logarithm of some number, and you do: (int)(logl(x)/logl(b))
.
Could either of the 2 produce incorrect results due to precision errors?
I would assume since long double
has 64 significant bits, both of the cases above should work correctly for all possible 64-bit integer values of x, but I am a bit skeptical of the logarithm, since there is an extra division step.
And if they are unreliable, what are good alternatives?
Sometimes double 3 may be stored as 2.99999999..., so when u want to cast it to integer, u may get wrong result(2 in this case).
It may be not good when u wanna find sqrt(a^2), because it may be equal to a-1 instead of a.
Usually I write such function:
It works right 100%)