(1.0/a*a) vs. (1.0*a/a) - what is the difference?

1
2
  (1.0*a/a == 1.0)
  (1.0/a*a == 1.0)


they all output 1.
but the first bool output true, while the second bool output false.

i think it's about the operator ==, but i don't exactly why.

could someone help?

thanks!

they all output 1.
(1.0*a/a == 1.0)
No, that code doesn't output anything.
oh sorry,
i want to say
1
2
double a = 9.0;
cout << 1.0*a/a << " " << 1.0/a*a << endl;

they are all 1.

however
 
cout << (1.0*a/a == 1.0) << " " << (1.0/a*a == 1.0) << endl;

output is 1 0.

i want to know why the second one is false.

sorry for that
Last edited on
It comes down to the difficulty of expressing values precisely in floating-point form.

Roughly speaking, it goes like this:
1.0/9.0 gives 0.111111
0.111111 * 9.0 gives 0.999999
0.999999 == 1.0 gives false.

Internally the values will be stored in binary rather than decimal which does change the details, though in this case the principle is the same.

edit: the other example,
1.0*a/a == 1.0
would go like this:
1.0 * 9.0 gives 9.0
9.0/9.0 gives 1.0
1.0 == 1.0 gives true

Last edited on

1
2
3
4
5
6
7
8
#include <iostream>
using std::cout;

int main()
{
  double a = 9.0;
  cout << (1.0*a/a == 1.0) << " " << (1.0/a*a == 1.0) << std::endl;
}


Comes out as "1 1" using a modern compiler (https://ideone.com/obfDkH ). I thing I'd expect a decent, modern compiler running under normal circumstances to spot those cancelling values and just not bother with them.

What compiler are you using?
Last edited on
re Moschops:
sorry another mistake. i'm using code::blocks.
it outputs 1 1 too if a = 9.0
however, it gives 1 0 if a = 99.0
(for a = 98 or 14, etc. it gives 1 1)

re Chervil:
wow, i think it's very important to know this concept.
if a = 99.0
compiler reads from left to right so (1.0/a*a) won't give 1 (because of the decimal point the compiler will store?)

however, compiler gives a true if a = 9.0
is it about my compiler? or i have misunderstood your explanation?

thanks!
Last edited on
code::blocks isn't a compiler. It's an IDE. code::blocks can be used with many different compilers. That's something for you to learn; what a compiler is, how they're used, and what compiler you are using.

Also read this: http://floating-point-gui.de/
Last edited on
thanks! i will check now!!
I gave the explanation before testing the program. When I did test it I found the result does depend on the value of a.
Topic archived. No new replies allowed.