On Apr 7, 1:15 am, Pete Becker <p...@versatilecoding.com> wrote:
> Jim Langston wrote:
> > It's not really the standard that's the issue I dont' think, it's just the
> > way floating point math works.
> Don't get paranoid. <g> There's a specific reason for this descrepancy.
But it is partially the standard at fault, since the standard
explicitly allows extended precision for intermediate results
(including, I think function return values, but I'm not sure
there).
> > In your particular case, those statements are close together, initializing f
> > and the comparison, so the compiler may be optimizing and comparing the same
> > thing. It all depends on how the compiler optimizes. Even something like:
> > double f = std::cos(x);
> > double g = std::cos(x);
> > std::cout << ( f == g ) << std::endl;
> > may output 1 or 0, depending on compiler optimization.
> It had better output 1, regardless of compiler optimizations.
I don't know about this particular case, but I've had similar
cases fail with g++. By default, g++ is even looser than the
standard allows. One could put forward the usual argument about
it not mattering how fast you get the wrong results, but in at
least some cases, the results that it gets by violating the
standard are also more precise

. (The problem is, of course,
that precise or not, they're not very predictable.)
> > You just cant count on floating point equality, it may work
> > sometimes, not others.
> The not-so-subtle issue here is that the compiler is permitted to do
> floating-point arithmetic at higher precision than the type requires. On
> the x86 this means that floating-point math is done with 80-bit values,
> while float is 32 bits and double is 64 bits. (The reason for allowing
> this is speed: x86 80-bit floating-point math is much faster than 64-bit
> math) When you store into a double, the stored value has to have the
> right precision, though. So storing the result of cos in a double can
> force truncation of a wider-than-double value. When comparing the stored
> value to the original one, the compiler widens the original out to 80
> bits, and the result is different from the original value. That's what's
> happening in the original example.
Question: if I have a function declared "double f()", is the
compiler also allowed to maintain extended precision, even
though I'm using the results of the expression in the return
statement to initialize a double? (G++ definitly does, at least
in some cases.)
> In your example, though, both results are stored, so when widened they
> should produce the same result. Some compilers don't do this, though,
> unless you tell them that they have to obey the rules (speed again).
OK. We're on the same wave length. I can confirm that g++ is
one of those compilers.
--
--
James Kanze (Gabi Software) email:
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34