Class FloatingPointComparer<T>
- Namespace
- Utils.Mathematics
- Assembly
- Utils.dll
Provides floating-point comparisons that allow for small deviations using a configurable interval. Implements only IComparer<T>: fuzzy equality cannot be used for hashing.
public class FloatingPointComparer<T> : IComparer<T> where T : struct, IFloatingPointIeee754<T>
Type Parameters
T
- Inheritance
-
FloatingPointComparer<T>
- Implements
-
IComparer<T>
- Inherited Members
- Extension Methods
Remarks
This comparer is intentionally non-transitive: two values that are each within Interval of a middle value may not be within Interval of each other. Do not use with SortedSet<T>, SortedDictionary<TKey, TValue>, or any algorithm that requires a total strict order.
Constructors
FloatingPointComparer(int)
Initializes a new instance of the FloatingPointComparer<T> class using a decimal precision.
public FloatingPointComparer(int precision)
Parameters
precisionintThe number of decimal places that must match.
FloatingPointComparer(T)
Initializes a new instance of the FloatingPointComparer<T> class with a custom interval.
public FloatingPointComparer(T interval)
Parameters
intervalTThe maximum allowed difference between two values.
Properties
Interval
Gets the tolerance interval used to consider two numbers equal.
public T Interval { get; }
Property Value
- T
Methods
Compare(T, T)
Compares two values, treating them as equal when their absolute difference is at most Interval.
public int Compare(T x, T y)
Parameters
xTyT
Returns
Remarks
Because this uses a tolerance zone, the ordering is not transitive:
Compare(a, b) == 0 and Compare(b, c) == 0 do not imply Compare(a, c) == 0.
ForPrecision(int)
Returns a cached FloatingPointComparer<T> for the specified decimal precision.
Repeated calls with the same precision return the same instance.
public static FloatingPointComparer<T> ForPrecision(int precision)
Parameters
precisionintThe number of decimal places that must match.