Not sure how to make the title more descriptive, so I'll just start with an example. I'm using the bit of code below which selects a direction from an enum, depending on which of the four axis form the smallest angle in comparison with a given direction.
static Direction VectorToDirection(Vector2 direction)
{
double upDiff = System.Math.Acos(Vector2.Dot(direction, -Vector2.UnitY));
double downDiff = System.Math.Acos(Vector2.Dot(direction, Vector2.UnitY));
double leftDiff = System.Math.Acos(Vector2.Dot(direction, -Vector2.UnitX));
double rightDiff = System.Math.Acos(Vector2.Dot(direction, Vector2.UnitX));
double smallest = System.Math.Min(System.Math.Min(upDiff, downDiff), System.Math.Min(leftDiff, rightDiff));
// This is the part I'm unsure about i.e.
// Comparing smallest with each value in turn
// To find out which of the four was "selected"
if (smallest == upDiff) return Direction.Up;
if (smallest == downDiff) return Direction.Down;
if (smallest == leftDiff) return Direction.Left;
return Direction.Right;
}
But I get the Resharper warning about floating point equality at the end. I'm guessing it should not be a problem due to the implementation of Min
, but was wondering if there might be a better idiom to solve this kind of problem besides comparing smallest
with each of the original values.