### nik1996's blog

By nik1996, history, 9 months ago, ,

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

 » 9 months ago, # | ← 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).
•  » » 9 months ago, # ^ |   0 Thanks for your advice!! Will keep that in mind next time.
 » 9 months ago, # | ← 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 )
•  » » 9 months ago, # ^ |   +41 Assuming that n and k are integers, I think (n+k-1)/k is more common.
•  » » 9 months ago, # ^ |   +26 That is ceil not floor.
•  » » » 9 months ago, # ^ |   +10 this is what happens when you type things on the phone
 » 9 months ago, # |   0 C++ has a builtin sqrtl that is much more precise than sqrt.
 » 9 months ago, # |   0 Use sqrtl(),it is more precise.