Float Point

#include <stdio.h>

int main()
{
float a=fabsf(0.7);
if (a<0.7){
printf("C");
}
else {
printf("C++");
}
return 0;
}

I CANNOT UNDERSTAND WHY IT IS PRINTING 'C' INSTEAD OF 'C'++.
First of al, use code tags when posting code. This makes your code easier to read.

Let's go over your code then.
First you have a float a, which you set to be the absolute value of 0.7 (this is what the function fabsf() does). Then you try to compare floating point numbers. This is generally a bad idea, because of inaccuracy issues. We can illustrate this by printing your variable a with a precision of 20 digits:
1
2
3
4
5
6
7
8
#include <iostream>
#include <iomanip>
#include <math.h>
int main()
{
    float a = fabsf(0.7);
    std::cout << std::setprecision(20) << a << std::endl;
}


This produces the output: 0.69999998807907104492
We can clearly see that, due to rounding errors, this value is smaller than 0.7
I suggest you write a special function for comparing floats.
Last edited on
I cannot understand why it is printing "C" instead of "C++"

Rounding error.

0.7 is a double, but a is a float.

The value 0.7 is not representable in binary floating point. This is analogous to how the rational number 1/3 can't be written exactly in decimal. The nearest representable (IEEE754) floating point number has a decimal value of 0.699999988079071044921875; this value is stored in a.

On the next line, the comparision a < 0.7 compares a float (that is, a), with a double (the literal 0.7). This causes a to be promoted to double, but its value is preserved through the conversion. Since double has more significant digits than float, it can represent a number closer to 0.7 ( precisely 0.6999999999999999555910790149937383830547332763671875 ), and so the comparision is true.

If you change 0.7 to 0.7f, the results will be as you expect.

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Last edited on
a fairly standard thing to do is

if( fabs(a-b) < eps) //they are effectively equal, if not exact
then equal stuff
else
not equal stuff

where eps can be your own value or something from the limits header depending on your usage. The idea is that you can come up with a value from 2 or more computations or sources but you want to know if they are equal give or take rounding/representation issues, so you have to check if they are close enough instead. Eps is usually very small.


Last edited on
Topic archived. No new replies allowed.