First, I know that floating point variables should not be compared "raw"
due to the way they're represented.  But the behavior I'm seeing has me
surprised.

Here's a small repo example:

-----------------------------------

#include <iostream>

using namespace std;

int main()
{
        float f1(4.94f + 0.2f), f2(5.14f), f3(4.94f), f4(0.2f), f5(f3 + f4);
        cout << "1) " << "5.14 < 5.14: " << (5.14 < 5.14) << endl;
        cout << "2) " << f1 << " < " << f1 << ": " << (f1 < f1) << endl;
        cout << "3) " << f2 << " < " << f2 << ": " << (f2 < f2) << endl;
        cout << "4) " << f1 << " < " << f2 << ": " << (f1 < f2) << endl;
        cout << "5) " << f2 << " < " << f1 << ": " << (f2 < f1) << endl;
        cout << "6) " << f2 << " < " << (f3 + f4) << ": " << (f2 < (f3 + f4) )
<< endl;
        cout << "7) " << f2 << " < " << f5 << ": " << (f2 < f5) << endl;
}

-----------------------------------

And here's the output from running it:

nick@nimble ~/test2 $ g++ FloatCompare.cpp && ./a.out
1) 5.14 < 5.14: 0
2) 5.14 < 5.14: 0
3) 5.14 < 5.14: 0
4) 5.14 < 5.14: 0
5) 5.14 < 5.14: 0
6) 5.14 < 5.14: 1
7) 5.14 < 5.14: 0


I'm very surprised by the result in #6.  #7 seems to be doing the same
thing, except that it uses a local variable to hold the sum.


Here's my GCC version:

nick@nimble ~/test2 $ gcc -v
Using built-in specs.
COLLECT_GCC=/usr/i686-pc-linux-gnu/gcc-bin/4.7.3/gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/i686-pc-linux-gnu/4.7.3/lto-wrapper
Target: i686-pc-linux-gnu
Configured
with: /var/tmp/portage/sys-devel/gcc-4.7.3-r1/work/gcc-4.7.3/configure
--host=i686-pc-linux-gnu --build=i686-pc-linux-gnu --prefix=/usr
--bindir=/usr/i686-pc-linux-gnu/gcc-bin/4.7.3
--includedir=/usr/lib/gcc/i686-pc-linux-gnu/4.7.3/include
--datadir=/usr/share/gcc-data/i686-pc-linux-gnu/4.7.3
--mandir=/usr/share/gcc-data/i686-pc-linux-gnu/4.7.3/man
--infodir=/usr/share/gcc-data/i686-pc-linux-gnu/4.7.3/info
--with-gxx-include-dir=/usr/lib/gcc/i686-pc-linux-gnu/4.7.3/include/g
++-v4 --with-python-dir=/share/gcc-data/i686-pc-linux-gnu/4.7.3/python
--enable-languages=c,c++,java --enable-obsolete --enable-secureplt
--disable-werror --with-system-zlib --disable-nls
--enable-checking=release --with-bugurl=https://bugs.gentoo.org/
--with-pkgversion='Gentoo 4.7.3-r1 p1.4, pie-0.5.5'
--enable-libstdcxx-time --enable-shared --enable-threads=posix
--enable-__cxa_atexit --enable-clocale=gnu --disable-multilib
--disable-altivec --disable-fixed-point --with-arch=i686
--enable-targets=all --enable-libgomp --enable-libmudflap
--disable-libssp --disable-libquadmath --enable-lto --without-cloog
--without-ppl
Thread model: posix
gcc version 4.7.3 (Gentoo 4.7.3-r1 p1.4, pie-0.5.5) 

I also have GCC 4.8 on my system and the result is the same.


Is this expected behavior?

Best regards,
Nick


Reply via email to