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

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

One lesson I have learned on last Div #3 contest is "avoid using pow() function in C++, it is can lead to Wrong Answer".

I am sharing this with a practical example:

This submission works only if you replace long long p = pow(n1, 3) + pow(mid, 3);

with long long p = n1 * n1 * n1 + mid * mid * mid;

I feel like it is useful to sare it !

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

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

Do you know why this happens?

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

It is mainly because pow function returns double and when we convert it to integer , sometimes it gives wrong answer due to ignoring the decimal part. For eg suppose if the returned value is 99.999999 then it will give answer as 99 whereas if the answer is 100.00001 it will be 100.For avoiding this I use this as it always gives correct answer:-

Code
»
6 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +19 Проголосовать: не нравится
»
6 лет назад, скрыть # |
 
Проголосовать: нравится +21 Проголосовать: не нравится

I never understand why people are amused by this 'problem' so much and even write blogs. It's simple — floating point functions, all of them, like pow and log or literally anything else, are not exact and shouldn't be used in integer tasks. Write your own algorithms like binary exponention or a for loop yourself.

»
6 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится -31 Проголосовать: не нравится

abs() is bad before C++11

»
6 лет назад, скрыть # |
 
Проголосовать: нравится +6 Проголосовать: не нравится

lol, just realized that there is a function called cbrt() which is short for cubic root.

So I was today years old when I learned that sqrt() has it's funny name because it calculates the square root.

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

practically you can expect double to precisely store 12 digits