Hi,
I have long int x, long int y and float f.
In a case x = 380, y = 38 and f = 0.1
when i make make the comparison
if(y >= x * y) cout << "true";
else cout << "false"
it prints false
i run my code on g++ (Ubuntu 4.3.3-5ubuntu4) 4.3.3
The short version:
Floating point numbers are represented internally in binary. It's impossible to precisely represent decimal 0.1 in binary using finite storage (it's 0.0(0011)). When you do the assignment, the compiler does its best to find an approximation to the value.
Naturally, since it's an approximation, multiplying another number by it will not give the same result as dividing by 10.
Actually, when x is multiplied by 0.1, the answer becomes float (because f is a float) because it is automatically casted(just google it), and when a data type changes to double or float, for some reason you end up with this extra .000000000001. I'm not sure why it does this but x * f actually ends up being 38.0000000001 which would make y >= x * f false.
Two things. In C++, "floating point" constants such as 0.1 are treated as doubles, not
floats, per the standard.
Second, the answer to your question is to read the link Duoas posted. The majority of
floating point numbers do not have exact representations in memory. Think about it --
there are an infinite number of floating point numbers since I can have an infinite number
of decimal places. It therefore stands to reason that to be able to precisely represent
every unique floating point number would require infinite memory.