Блог пользователя nik1996

Автор nik1996, история, 5 лет назад, По-английски

Hi all,

Recently I was solving problem Sad Powers. In the editorial of the problem it is mentioned that sqrt() function of c++ has some precision issues. On using the function in my problem on some value gives me wrong answer. After looking others solution I observed that some have used additional checks. e.g. If square root of value x is required then many solutions have checked for both x and (x-1) /(x+1). I could not understand why that additional check is required.

Can anybody please tell why this additional check is required or what are the issues with sqrt() function?

Thanks!!

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
5 лет назад, # |
Rev. 3   Проголосовать: нравится +2 Проголосовать: не нравится

Remember that sqrt() has 4 type of parameters two of them is sqrt(double x) and sqrt(long double x). If you feed the parameter with long long type, the function will call sqrt(double x). Which means you will losing precision if the long long number > +- 10^14 because of the precision of double type holds.
You want to use the one with long double type as it will hold the precision of long long number AND the floating point (as good as doubles are).
To use it, simply call it by typecast the number to long double such as sqrt(1.0L * x).

You can look at my submission for example (I just recently solved it too).

»
5 лет назад, # |
Rev. 2   Проголосовать: нравится +10 Проголосовать: не нравится

Floating points will always have precision errors — avoid them if you can.

E.g instead of ceil(n/k)

something like (n%k==0? n/k : n/k+1 )

»
5 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

C++ has a builtin sqrtl that is much more precise than sqrt.

»
5 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Use sqrtl(),it is more precise.