Evil code, please explain

It seems not an openframeworks issue, but please someone give me an answer:

running this code works fine in xcode, but running it on windows7, codeblocks giving me unexpected results:

code:

void ofApp::update(){

float p1x = ofRandomf();
float p1y = ofRandomf();
float p2x = ofRandomf();
float p2y = ofRandomf();

float dA = ofDist(p1x, p1y, p2x, p2y);
float dB = ofDist(p1x, p1y, p2x, p2y);
//float dA = sqrtf((p1x - p2x) * (p1x - p2x) + (p1y - p2y) * (p1x - p2y));
//float dB = sqrtf((p1x - p2x) * (p1x - p2x) + (p1y - p2y) * (p1x - p2y));

printf("%i :: %f %f\n", dA < dB, dA, dB);

}

output:

1 :: 0.444509 0.444509
1 :: 0.532536 0.532536
0 :: 0.396982 0.396982
0 :: 1.649467 1.649467
0 :: 1.305453 1.305453
1 :: 0.876246 0.876246
0 :: 1.036359 1.036359
0 :: 1.136453 1.136453
1 :: 0.477681 0.477681
0 :: 0.719740 0.719740
1 :: 1.751981 1.751981

sqrtf((p1x…) version works fine,
but when I use my own function:

float ofApp::dst(float p1x, float p1y, float p2x, float p2y)
{
return sqrtf((p1x - p2x) * (p1x - p2x) + (p1y - p2y) * (p1y - p2y));
}

the same bug appears…

in visual studio its working fine again…

Hi,
I read once that, due to the nature of the float or double values, it’s not a good idea to test the equality between two of them (example). This can produce unexpected behaviour. I don’t know why exactly. The same error must append when using inequality / strict inequality.
In your case, you can perhaps test something like dA < dB - 0.000001

2 Likes

I love the sin(float(pi)) !

Thanks for your answer !
The article is excellent and frightening at the same time, I feel I should never ask :smile:
The strange thing in my case is that if I calculate the value “right next to” the comparison, i get the normal behaviour, but if I use a function to calculate the same thing the floating point error appears.
Also it is seems to be a compiler issue, because xcode or VS doing it “right”…