result of 'float' - 'float' ???

Hi,
I have a calculation with two float numbers and I don't understand why the result is actually what it is?

1
2
3
4
5
6
7
8
9
int main(void) {

float a = -1.5, b=-1.4;
float c = a-b;

cout << setprecision(7) << " a = " << scientific << a << " b = " << b << "  c = " << c;

return 0;
}


and I get

a = -1.5000000e+00 b = -1.4000000e+00  c = -1.0000002e-01


why isn't c = -1.0000000e-01 ?
Floating point numbers are only approximations of Real numbers. They are not exact.
Note that the representation of 0.1 in binary is infinite (periodic) thus it cannot be held in the limited memory of float. Of course, it could be represented as a fraction, but that's not how floats work.
I know that they are only approximations... but I thought that the calculation was "exact" and the display/internal saving of the numbers are approximations (machine accuracy)?

edit:
@hamsterman:
So even if I write the numbers exactly they are internally stored as approximations? That would explain the "easy" calculation going wrong. So every "noninteger" number is only an approximation, even the "easy" ones?
/edit
Last edited on
Have you tried:
1
2
float a = -1.5f, b=-1.4f;
float c = a-b;

I think your problem is that you're creating them as doubles.
yes, also tried with a = -1.5f ... same result.
So every "noninteger" number is only an approximation, even the "easy" ones?


Yes. (I guess this isn't true, I was just over simplifying)

Reading these might be helpful:

http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18
Last edited on

So every "noninteger" number is only an approximation, even the "easy" ones?


Not every, but the "easy" ones you think are easy, are different from the "easy" ones for the computer.
E.g. these are some example easy floats that are represented exactly:


0.5
0.25
0.125
0.625

What Every Computer Scientist Should Know About Floating-Point Arithmetic
http://docs.sun.com/source/806-3568/ncg_goldberg.html
Some integers can't be represented exactly by float. IINM, the float set doesn't contain any of the following:
* Odd numbers higher than 2^24.
* Non-divisors of 4 higher than 2^25.
* Non-divisors of 8 higher than 2^26.
Thank you everyone!
@Disch: The C++ FAQ was really great!
@rapidcoder: I have other calculations where mainly the numbers you mentioned are used. That was the reason for my question, since nearly all my calculations are exact (with 0.5 0.25... numbers) but some are not exact (with 0.1 1.4 ... numbers). Now I know I have to be careful with floating-point numbers.
Topic archived. No new replies allowed.