J0hj0h J0hj0h - 4 months ago 21
C++ Question

Difference between C++ snippets that should be identical

For a homework for Computer Graphics we have to write a function, that determines if a point

is on the left side of an edge
. Now my partner and I have two different versions of this function that produce different results, despite calculating the same thing.

Snippet 1:

// The direction of the line from p1 to p:
float lineX = p.x - p1.x;
float lineY = p.y - p1.y;
// The direction of the triangle's edge from p1 to p2:
float edgeX = p2.x - p1.x;
float edgeY = p2.y - p1.x;

// The z component of the cross product (line x edge):
float F = lineX * edgeY - lineY * edgeX;

Snippet 2:

float x = p.x;
float y = p.y;
float X = p1.x;
float Y = p1.y;
float dX = p2.x - p1.x;
float dY = p2.y - p1.y;

float F = ((x-X) * dY - (y-Y) * dX);

I know that floating point operations are not commutative nor associative. However, in my understanding, the order of calculations should be exactly the same, since
lineX = x-X
edgeX = dX

Is there some compiler optimization that messes with the calculations?


Copy and paste error:

float edgeX = p2.x - p1.x;
float edgeY = p2.y - p1.x;