Why does Std::Ceil produce different results for float and double?

Asked

Viewed 65 times

5

Follows the code:

#include <iostream>
#include<math.h>

using namespace std;

int main()
{   
    float calculo = 4.347 * 20 * 100;
    double calculo2 = 4.347 * 20 * 100;
    cout<<std::ceil(calculo)<<std::endl;
    cout<<std::ceil(calculo2)<<std::endl;
    return 0;
}
Resultado para a variável em float: 8694
Resultado para a variável em double: 8695

Can someone explain to me why this happens?

The value for double variable should not be 8694 either, since the calculation results in a value without decimal places.

1 answer

6


These types are not accurate, so you get approximate values. If you want accuracy you cannot use either. Who uses these types of data should know that the values are approximate, never exact.

The ceil() has rules of which values are considered to go to the integer above or below, with different precision the same number that looks equal is actually different and you’ve caught a case that the greater precision makes it hang over the other side.

There is another problem. The two expressions are made as double. The default literal when it has decimal is the double, when you want to use the float need to use suffix f number. So even in the first case every account is made with double precision, and when it will assign it converts to float, which causes a loss. For me a language failure, but that occurs. But it does not cause the problem pointed out, I am putting as a curiosity.

If you had done the account in hand you wouldn’t have this error. But the problem is to use an inaccurate type when you want accuracy.

It’s kind of the same problem as comparison of values with binary floating point (float and double) even of the same type, the number is not represented exactly. The same type could make a difference depending on how you arrived at it.

There are more details on What is the correct way to use the float, double and decimal types?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.