microsoft-visualbasic-runtime/Extensions/Math/NumberEqualityComparer.vb

88 lines
2.9 KiB
VB.net
Raw Normal View History

2020-05-21 22:27:25 +08:00
#Region "Microsoft.VisualBasic::96dd3f761a42c567a8614b43094c5bd0, Microsoft.VisualBasic.Core\Extensions\Math\NumberEqualityComparer.vb"
2018-08-02 20:14:48 +08:00
' Author:
'
' asuka (amethyst.asuka@gcmodeller.org)
' xie (genetics@smrucc.org)
' xieguigang (xie.guigang@live.com)
'
' Copyright (c) 2018 GPL3 Licensed
'
'
' GNU GENERAL PUBLIC LICENSE (GPL3)
'
'
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU General Public License as published by
' the Free Software Foundation, either version 3 of the License, or
' (at your option) any later version.
'
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' GNU General Public License for more details.
'
' You should have received a copy of the GNU General Public License
' along with this program. If not, see <http://www.gnu.org/licenses/>.
' /********************************************************************************/
' Summaries:
' Class NumberEqualityComparer
'
' Properties: DeltaTolerance
'
' Constructor: (+2 Overloads) Sub New
' Function: (+2 Overloads) Equals, GetHashCode, ToString
'
'
' /********************************************************************************/
#End Region
Imports System.Runtime.CompilerServices
Imports stdNum = System.Math
2018-08-02 20:14:48 +08:00
Namespace Math
''' <summary>
''' 当两个数的误差值的绝对值小于阈值的时候认为两个数字相等
''' </summary>
Public Class NumberEqualityComparer : Implements IEqualityComparer(Of Double)
Public Property DeltaTolerance As Double
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Sub New(tolerance As Double)
DeltaTolerance = tolerance
End Sub
Sub New()
Call Me.New(0.00001)
End Sub
Public Overrides Function ToString() As String
Return $"|a-b| <= {DeltaTolerance}"
End Function
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Overloads Function Equals() As GenericLambda(Of Double).IEquals
Return AddressOf Equals
End Function
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Overloads Function Equals(x As Double, y As Double) As Boolean Implements IEqualityComparer(Of Double).Equals
Return stdNum.Abs(x - y) <= _DeltaTolerance
2018-08-02 20:14:48 +08:00
End Function
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Overloads Function GetHashCode(obj As Double) As Integer Implements IEqualityComparer(Of Double).GetHashCode
Return obj.GetHashCode
End Function
End Class
End Namespace