1 Imports System.Runtime.CompilerServices
2
3 Namespace Math
4
5     ''' <summary>
6     ''' 当两个数的误差值的绝对值小于阈值的时候认为两个数字相等
7     ''' </summary>
8     Public Class NumberEqualityComparer : Implements IEqualityComparer(Of Double)
9
10         Public Property DeltaTolerance As Double
11
12         <MethodImpl(MethodImplOptions.AggressiveInlining)>
13         Sub New(tolerance As Double)
14             DeltaTolerance = tolerance
15         End Sub
16
17         Sub New()
18             Call Me.New(0.00001)
19         End Sub
20
21         Public Overrides Function ToString() As String
22             Return $"|a-b| <= {DeltaTolerance}"
23         End Function
24
25         <MethodImpl(MethodImplOptions.AggressiveInlining)>
26         Public Overloads Function Equals() As GenericLambda(Of Double).IEquals
27             Return AddressOf Equals
28         End Function
29
30         <MethodImpl(MethodImplOptions.AggressiveInlining)>
31         Public Overloads Function Equals(x As Double, y As DoubleAs Boolean Implements IEqualityComparer(Of Double).Equals
32             Return Math.Abs(x - y) <= _DeltaTolerance
33         End Function
34
35         <MethodImpl(MethodImplOptions.AggressiveInlining)>
36         Public Overloads Function GetHashCode(obj As DoubleAs Integer Implements IEqualityComparer(Of Double).GetHashCode
37             Return obj.GetHashCode
38         End Function
39     End Class
40
41 End Namespace