L
lilburne
Mattias said:It is strange though that static_cast change the result in that
unexpected way.
On Linux r1 and r2 will differ
double tmp = val * multiplier;
int r1 = static_cast<int> (tmp);
int r2 = static_cast<int> (val * multiplier);
Shrug - you'd expect the optimizer to only do the
calculation once, and in any case to produce the same code.
The only way that you can really determine what is going on
is to examine the compiler output (on g++ use the -S
option). But all FP calculations and particularly
comparisons should be done with caution, you should always
be prepared for inaccuracy and code for it.
An example of FP problems with division on my system.
#include <iostream>
int main()
{
double d = 123456.789012345;
double e = d;
cout.precision(20);
cout << d << endl;
d *= 10.0;
cout << d << endl;
cout << "attempting multiplication" << endl;
double f = d;
d *= 0.1;
cout << d << endl;
if (e != d){
cout << "Not equal" << endl;
}
cout << "attempting division" << endl;
f /= 10.0;
cout << f << endl;
if (e != f){
cout << "Not equal" << endl;
}
return 0;
}