Re: std::sort causes segfault when sorting class arrays
On Mar 1, 9:00 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
Juha Nieminen wrote:
Kai-Uwe Bux wrote:
Well, I just had this program:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main ( void ) {
double x = 1;
double y = 1;
cout
<< boolalpha
<< ( sin(x)+cos(y) == sin(x)+cos(y) ) << '\n';
}
and the output was "false".
I honestly can't understand what's happening there. Even if
it's changed to this:
#include <iostream>
#include <iomanip>
#include <cmath>
double f(double x, double y)
{
return std::sin(x) + std::cos(y);
}
int main ( void ) {
double x = 1;
double y = 1;
std::cout << std::boolalpha
<< ( f(x, y) == f(x, y) ) << std::endl;
}
it still prints false. [..]
I don't know what you're talking about, guys. I just took
your code, plugged it into my test project, compiled, ran, and
got 'true'. Changed FP settings, changed to optimized, same
thing. Maybe Visual C++ 2008 is wrong somehow, and I am
supposed to get 'false'?
What compiler, what hardware? Can you post the assembly?
You're supposed to get true, at least if the floating point
hardware doesn't to any random rounding. (I think we all agree
that if you change the rounding mode of the FPU between the
calls, all bets are off.) This is a well known issue with g++
(I'd call it a bug, but it is intentional), which optimizes more
than is allowed by the standard.
Note that if you change the code to manually inline the
functions (and thus eliminate the initialization of the double
return value), the standard does allow the results not to
compare equal. Curiously enough, with g++, it's more likely to
work in the case where it's not guaranteed; unless the
expression requires enough temporaries to spill to memory,
everything will be done with 64 bits precision, and you'll get
the wrong results. The problem here is that the compiler cannot
see the register use in the function, so after the first call,
it must assume that all floating point registers are used, and
spill those results to memory. It then (incorrectly) compares
the 64 bit results with the truncated results.
On an Intel, and probably on other processors which do all
floating point arithmetic with extended precision by default.
On a Sparc (which doesn't have a 64 bit precision double), there
is no problem.
--
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