Phantom_Dreams's blog

By Phantom_Dreams, history, 4 hours ago, In English

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?

  • Vote: I like it
  • +4
  • Vote: I do not like it

»
3 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

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:

int SQRT(T x) {
    int maybe = sqrt(x);
    return (1ll * (maybe + 1) * (maybe + 1) == x) ? maybe + 1 : maybe;
}

It works right 100%)