float long comparison

Sep 14, 2009 at 11:02am
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


how can i overcome this problem? any idea???
Sep 14, 2009 at 11:36am
Learn math!

x * y = 380 * 38 = 14440.

And do you think is it true 38 >= 14440?
Sep 14, 2009 at 5:31pm
upps, mistyping, it was supposed to be

if(y >= x * f) cout << "true";
else cout << "false"
Sep 14, 2009 at 5:36pm
Ah, you've reached the point where you need to learn

What Every Computer Scientist Should Know About Floating-Point Arithmetic
http://docs.sun.com/source/806-3568/ncg_goldberg.html
Sep 14, 2009 at 5:46pm
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.
Last edited on Sep 14, 2009 at 5:50pm
Sep 15, 2009 at 11:39pm
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.
Last edited on Sep 16, 2009 at 8:11pm
Sep 16, 2009 at 2:07pm
@rvbman:

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.
Topic archived. No new replies allowed.