feat: float & Vector2D.ApproximatelyEquals
This commit is contained in:
parent
a60f79f12b
commit
d40183db65
|
@ -0,0 +1,22 @@
|
|||
namespace Syntriax.Engine.Core;
|
||||
|
||||
public static class FloatExtensions
|
||||
{
|
||||
public static bool ApproximatelyEquals(this float a, float b)
|
||||
=> ApproximatelyEquals(a, b, float.Epsilon);
|
||||
public static bool ApproximatelyEquals(this float a, float b, float epsilon)
|
||||
{
|
||||
if (a == b)
|
||||
return true;
|
||||
|
||||
const float floatNormal = (1 << 23) * float.Epsilon;
|
||||
float absA = Math.Abs(a);
|
||||
float absB = Math.Abs(b);
|
||||
float diff = Math.Abs(a - b);
|
||||
|
||||
if (a == 0.0f || b == 0.0f || diff < floatNormal)
|
||||
return diff < (epsilon * floatNormal);
|
||||
|
||||
return diff / Math.Min(absA + absB, float.MaxValue) < epsilon;
|
||||
}
|
||||
}
|
|
@ -27,4 +27,7 @@ public static class Vector2DExtensions
|
|||
public static float Cross(this Vector2D left, Vector2D right) => Vector2D.Cross(left, right);
|
||||
public static float AngleBetween(this Vector2D left, Vector2D right) => Vector2D.Angle(left, right);
|
||||
public static float Dot(this Vector2D left, Vector2D right) => Vector2D.Dot(left, right);
|
||||
|
||||
|
||||
public static bool ApproximatelyEquals(this Vector2D left, Vector2D right, float epsilon = float.Epsilon) => Vector2D.ApproximatelyEquals(left, right, epsilon);
|
||||
}
|
||||
|
|
|
@ -49,5 +49,8 @@ public record Vector2D(float X, float Y)
|
|||
public static float Angle(Vector2D left, Vector2D right) => MathF.Acos(Dot(left, right) / (Length(left) * Length(right)));
|
||||
public static float Dot(Vector2D left, Vector2D right) => left.X * right.X + left.Y * right.Y;
|
||||
|
||||
public static bool ApproximatelyEquals(Vector2D left, Vector2D right, float epsilon = float.Epsilon)
|
||||
=> left.X.ApproximatelyEquals(right.X, epsilon) && left.Y.ApproximatelyEquals(right.Y, epsilon);
|
||||
|
||||
public override string ToString() => $"{nameof(Vector2D)}({X}, {Y})";
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue