Re: Floating Point comparison problem
arnuld wrote:
Next month I will start to work on a C++ based Software named CAT++ which
is going to provide FORTRAN like arrays in C++ and will be used within
Scientific Community and hence will heavily depend on
Numerical-Computations. I was reading 29.16 ans 29.17 sections of FAQs:
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16
as a test, I just tried this program on Linux, GCC 4.2.2 and
it gave me 2 different results:
#include <iostream>
#include <string>
#include <vector>
int main()
{
const double x = 0.05;
const double y = 0.07;
const double z = x + y;
const double key_num = x + y;
if( key_num == z )
{
std::cout << "==\n";
}
else
{
std::cout << "!=\n";
}
return 0;
}
========== OUTPUT =============
/home/arnuld/programs $ g++ -ansi -pedantic -Wall -Wextra test2.cpp
/home/arnuld/programs $ ./a.out
==
/home/arnuld/programs $
it always outputs == , Now i changed key_num to this:
const double key_num = 0.12;
and this program now always outputs !=
Which seems normal to me. I certainly wouldn't expect anything
else.
/home/arnuld/programs $ g++ -ansi -pedantic -Wall -Wextra test2.cpp
/home/arnuld/programs $ ./a.out
!=
/home/arnuld/programs $
As FAQ explains Floating-Point is inaccurate but my project is
heavily oriented towards number-crunching, so I was thinking
of stop developing that sofwtare in C++ and simply use FORTRAN
for this specific application in a special domain.
It's not so much a question of floating point being inaccurate
per se, but rather that it follows somewhat different rules than
the real numbers. You can use them to simulate real numbers,
but you have to know what you are doing. (The term "inaccurate"
here generally should be interpeted to mean that they are an
inaccurate simulation of the real numbers.)
Changing to Fortran won't change anything, of course, because
the problem isn't with the language; it's with the way floating
point is implemented in hardware.
Until you've read and understood "What Every Computer Scientist
Should Know About Floating-Point Arithmetic"
(http://docs.sun.com/source/806-3568/ncg_goldberg.html), you
shouldn't even try to do anything with float or double. (But
note that that article is only an introduction. If you want to
write complex numeric applications, you'll need to know a lot
more.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34