Single.Equals Single.Equals Single.Equals Single.Equals Method

定义

返回一个值,该值指示 Single 的两个实例是否表示同一个值。Returns a value indicating whether two instances of Single represent the same value.

重载

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。Returns a value indicating whether this instance is equal to a specified object.

Equals(Single) Equals(Single) Equals(Single) Equals(Single)

返回一个值,该值指示此实例和指定的 Single 对象是否表示相同的值。Returns a value indicating whether this instance and a specified Single object represent the same value.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。Returns a value indicating whether this instance is equal to a specified object.

public:
 override bool Equals(System::Object ^ obj);
public override bool Equals (object obj);
override this.Equals : obj -> bool
Public Overrides Function Equals (obj As Object) As Boolean

参数

obj
Object Object Object Object

与此实例进行比较的对象。An object to compare with this instance.

返回

如果 trueobj 的实例并且等于此实例的值,则为 Single;否则为 falsetrue if obj is an instance of Single and equals the value of this instance; otherwise, false.

示例

下面的代码示例演示了Equals方法。The following code example demonstrates the Equals method.

obj1 = (Single)500;

if ( a.Equals( obj1 ) )
{
   Console::WriteLine( "The value type and reference type values are equal." );
}
obj1 = (Single)500;
if (a.Equals(obj1)) {
    Console.WriteLine("The value type and reference type values are equal.");
}
Obj1 = CType(500, Single)

If A.Equals(Obj1) Then
    Console.WriteLine("The value type and reference type values are equal.")
End If

注解

Equals应谨慎使用,使用方法,因为两个看似相等的值可能是由于两个值的精度不同不相等。The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. 下面的示例报告Single值.3333 和Single返回除以 1 3 是否不相等。The following example reports that the Single value .3333 and the Single returned by dividing 1 by 3 are unequal.

// Initialize two floats with apparently identical values
float float1 = .33333f;
object float2 = 1/3;
// Compare them for equality
Console.WriteLine(float1.Equals(float2));    // displays false
' Initialize two singles with apparently identical values
Dim single1 As Single = .33333
Dim single2 As Object = 1/3
' Compare them for equality
Console.WriteLine(single1.Equals(single2))    ' displays False

而不是比较相等性,建议采用的一种方法是定义可接受两个值之间的差异的边距 (如。 01%的值之一)。Rather than comparing for equality, one recommended technique involves defining an acceptable margin of difference between two values (such as .01% of one of the values). 如果两个值之间的差的绝对值是小于或等于该边距,不同之处很可能是由于精度的不同,并且,因此,这些值很可能是相等。If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be due to differences in precision and, therefore, the values are likely to be equal. 下面的示例使用此技术比较.33333 和 1/3,这两个Single前面的代码示例找到不相等的值。The following example uses this technique to compare .33333 and 1/3, the two Single values that the previous code example found to be unequal.

// Initialize two floats with apparently identical values
float float1 = .33333f;
object float2 = (float) 1/3;
// Define the tolerance for variation in their values
float difference = Math.Abs(float1 * .0001f);

// Compare the values
// The output to the console indicates that the two values are equal
if (Math.Abs(float1 - (float) float2) <= difference)
   Console.WriteLine("float1 and float2 are equal.");
else
   Console.WriteLine("float1 and float2 are unequal.");
' Initialize two singles with apparently identical values
Dim single1 As Single = .33333
Dim single2 As Object = 1/3
' Define the tolerance for variation in their values
Dim difference As Single = Math.Abs(single1 * .0001f)

' Compare the values
' The output to the console indicates that the two values are equal
If Math.Abs(single1 - CSng(single2)) <= difference Then
   Console.WriteLine("single1 and single2 are equal.")
Else
   Console.WriteLine("single1 and single2 are unequal.")
End If

在这种情况下,值相等。In this case, the values are equal.

备注

因为Epsilon定义的最小的表达式必须大于差异的距其范围是接近于零的正值, EpsilonBecause Epsilon defines the minimum expression of a positive value whose range is near zero, the margin of difference must be greater than Epsilon. 通常情况下,它是比EpsilonTypically, it is many times greater than Epsilon.

超出有案可稽的精度的浮点数的精度是特定于实现和.NET Framework 版本。The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of the .NET Framework. 因此,两个特定数字的比较可能会更改的.NET Framework 版本之间,因为数字的内部表示形式的精度可能会更改。Consequently, a comparison of two particular numbers might change between versions of the .NET Framework because the precision of the numbers' internal representation might change.

调用方说明

编译器重载解析行为的两个明显的差异可能会考虑Equals(Object)方法重载。Compiler overload resolution may account for an apparent difference in the behavior of the two Equals(Object) method overloads. 如果之间的隐式转换obj自变量和一个Single定义和自变量类型不是Object,编译器可能会执行隐式转换和调用Equals(Single)方法。If an implicit conversion between the obj argument and a Single is defined and the argument is not typed as an Object, compilers may perform an implicit conversion and call the Equals(Single) method. 否则,调用方法Equals(Object)方法,它始终返回false如果其obj参数不是Single值。Otherwise, they call the Equals(Object) method, which always returns false if its obj argument is not a Single value. 下面的示例说明了两个方法重载之间的行为差异。The following example illustrates the difference in behavior between the two method overloads. 在除所有基元数值类型的情况下Double在 Visual Basic 和除DecimalDouble在 C# 中,第一次比较返回true因为编译器会自动执行扩大转换和调用Equals(Single)方法,而第二个比较返回false因为编译器将调用Equals(Object)方法。In the case of all primitive numeric types except for Double in Visual Basic and except for Decimal and Double in C#, the first comparison returns true because the compiler automatically performs a widening conversion and calls the Equals(Single) method, whereas the second comparison returns false because the compiler calls the Equals(Object) method.

[!code-csharpSystem.Single.Equals#2] [!code-vbSystem.Single.Equals#2][!code-csharpSystem.Single.Equals#2] [!code-vbSystem.Single.Equals#2]

另请参阅

Equals(Single) Equals(Single) Equals(Single) Equals(Single)

返回一个值,该值指示此实例和指定的 Single 对象是否表示相同的值。Returns a value indicating whether this instance and a specified Single object represent the same value.

public:
 virtual bool Equals(float obj);
public bool Equals (float obj);
override this.Equals : single -> bool
Public Function Equals (obj As Single) As Boolean

参数

obj
Single Single Single Single

与此实例进行比较的对象。An object to compare with this instance.

返回

如果 true 与此实例相等,则为 obj;否则为 falsetrue if obj is equal to this instance; otherwise, false.

实现

注解

此方法实现System.IEquatable<T>接口,并且执行略微优于Equals因为它不具有要转换obj参数的对象。This method implements the System.IEquatable<T> interface, and performs slightly better than Equals because it does not have to convert the obj parameter to an object.

扩大转换Widening Conversions

具体取决于您的编程语言,有可能对代码Equals方法的参数类型包含的位数少于 (是更窄) 比实例类型。Depending on your programming language, it might be possible to code an Equals method where the parameter type has fewer bits (is narrower) than the instance type. 这可能是因为某些编程语言执行表示具有任意数量的位的实例作为类型参数的隐式扩大转换。This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance.

例如,假设实例类型是Single且参数类型为Int32For example, suppose the instance type is Single and the parameter type is Int32. Microsoft C# 编译器将生成表示形式的参数值的说明Single对象,并生成Single.Equals(Single)进行比较的实例的值和参数加宽表示形式的方法。The Microsoft C# compiler generates instructions to represent the value of the parameter as a Single object, and then generates a Single.Equals(Single) method that compares the values of the instance and the widened representation of the parameter.

请查阅您的编程语言的文档以确定其编译器是否执行数值类型的隐式扩大转换。Consult your programming language's documentation to determine if its compiler performs implicit widening conversions of numeric types. 有关详细信息,请参阅类型转换表主题。For more information, see the Type Conversion Tables topic.

在比较中的精度Precision in Comparisons

Equals应谨慎使用,使用方法,因为两个看似相等的值可能是由于两个值的精度不同不相等。The Equals method should be used with caution, because two apparently equivalent values can be unequal because of the differing precision of the two values. 下面的示例报告Single值.3333 和Single返回除以 1 3 是否不相等。The following example reports that the Single value .3333 and the Single returned by dividing 1 by 3 are unequal.

// Initialize two floats with apparently identical values
float float1 = .33333f;
float float2 = 1/3;
// Compare them for equality
Console.WriteLine(float1.Equals(float2));    // displays false
' Initialize two singles with apparently identical values
Dim single1 As Single = .33333
Dim single2 As Single = 1/3
' Compare them for equality
Console.WriteLine(single1.Equals(single2))    ' displays False

一次比较技术,可避免比较相等性涉及定义两个值之间的差异的可接受幅度与相关的问题 (如。 01%的值之一)。One comparison technique that avoids the problems associated with comparing for equality involves defining an acceptable margin of difference between two values (such as .01% of one of the values). 如果两个值之间的差的绝对值是小于或等于该边距的区别是,可能需要的精度之间的差异的结果,并且,因此,值很可能相等。If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be an outcome of differences in precision and, therefore, the values are likely to be equal. 下面的示例使用此方法比较.33333 和 1/3,这两种Single前面的代码示例找到不相等的值。The following example uses this technique to compare .33333 and 1/3, which are the two Single values that the previous code example found to be unequal.

// Initialize two floats with apparently identical values
float float1 = .33333f;
float float2 = (float) 1/3;
// Define the tolerance for variation in their values
float difference = Math.Abs(float1 * .0001f);

// Compare the values
// The output to the console indicates that the two values are equal
if (Math.Abs(float1 - float2) <= difference)
   Console.WriteLine("float1 and float2 are equal.");
else
   Console.WriteLine("float1 and float2 are unequal.");
' Initialize two singles with apparently identical values
Dim single1 As Single = .33333
Dim single2 As Single = 1/3
' Define the tolerance for variation in their values
Dim difference As Single = Math.Abs(single1 * .0001f)

' Compare the values
' The output to the console indicates that the two values are equal
If Math.Abs(single1 - single2) <= difference Then
   Console.WriteLine("single1 and single2 are equal.")
Else
   Console.WriteLine("single1 and single2 are unequal.")
End If

在这种情况下,值相等。In this case, the values are equal.

备注

因为Epsilon定义的最小的表达式必须大于差异的距其范围是接近于零的正值, EpsilonBecause Epsilon defines the minimum expression of a positive value whose range is near zero, the margin of difference must be greater than Epsilon. 通常情况下,它是比EpsilonTypically, it is many times greater than Epsilon. 因此,我们建议不要使用Epsilon比较时Double值是否相等。Because of this, we recommend that you do not use Epsilon when comparing Double values for equality.

另一种技术能够避免与比较相等性相关的问题涉及比较两个浮点数与某些绝对值的数值之间的差异。A second technique that avoids the problems associated with comparing for equality involves comparing the difference between two floating-point numbers with some absolute value. 其差异是小于或等于该绝对值的数值,如果数字相等。If the difference is less than or equal to that absolute value, the numbers are equal. 如果超出该时间,则数字不相等。If it is greater, the numbers are not equal. 若要执行此操作的一种方法是任意选择一个绝对值。One way to do this is to arbitrarily select an absolute value. 但是,这是有问题,,因为差异的可接受幅度取决于度量值的Single值。However, this is problematic, because an acceptable margin of difference depends on the magnitude of the Single values. 第二种方式利用某个设计功能上的浮点格式:两个浮点值的整数表示形式中的尾数组件之间的差异指示分隔的两个值的可能的浮点值数。A second way takes advantage of a design feature of the floating-point format: The difference between the mantissa components in the integer representations of two floating-point values indicates the number of possible floating-point values that separates the two values. 例如,0.0 之间的差异并Epsilon为 1,因为Epsilon使用时是最小的可表示值Single其值为零。For example, the difference between 0.0 and Epsilon is 1, because Epsilon is the smallest representable value when working with a Single whose value is zero. 下面的示例使用此方法比较.33333 和 1/3,这两种Double的值与前面的代码示例Equals(Single)方法找到不相等。The following example uses this technique to compare .33333 and 1/3, which are the two Double values that the previous code example with the Equals(Single) method found to be unequal. 请注意,该示例使用BitConverter.GetBytesBitConverter.ToInt32方法将单精度浮点值转换为整数表示形式。Note that the example uses the BitConverter.GetBytes and BitConverter.ToInt32 methods to convert a single-precision floating-point value to its integer representation.

using System;

public class Example
{
   public static void Main()
   {
      float value1 = .1f * 10f;
      float value2 = 0f;
      for (int ctr = 0; ctr < 10; ctr++)
         value2 += .1f;
         
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2,
                        HasMinimalDifference(value1, value2, 1));
   }

   public static bool HasMinimalDifference(float value1, float value2, int units)
   {
      byte[] bytes = BitConverter.GetBytes(value1);
      int iValue1 = BitConverter.ToInt32(bytes, 0);
      
      bytes = BitConverter.GetBytes(value2);
      int iValue2 = BitConverter.ToInt32(bytes, 0);
      
      // If the signs are different, return false except for +0 and -0.
      if ((iValue1 >> 31) != (iValue2 >> 31))
      {
         if (value1 == value2)
            return true;
          
         return false;
      }

      int diff = Math.Abs(iValue1 - iValue2);

      if (diff <= units)
         return true;

      return false;
   }
}
// The example displays the following output:
//        1 = 1.00000012: True
Module Example
   Public Sub Main()
      Dim value1 As Single = .1 * 10
      Dim value2 As Single = 0
      For ctr As Integer =  0 To 9
         value2 += CSng(.1)
      Next
               
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2,
                        HasMinimalDifference(value1, value2, 1))
   End Sub

   Public Function HasMinimalDifference(value1 As Single, value2 As Single, units As Integer) As Boolean
      Dim bytes() As Byte = BitConverter.GetBytes(value1)
      Dim iValue1 As Integer =  BitConverter.ToInt32(bytes, 0)
      
      bytes = BitConverter.GetBytes(value2)
      Dim iValue2 As Integer =  BitConverter.ToInt32(bytes, 0)
      
      ' If the signs are different, Return False except for +0 and -0.
      If ((iValue1 >> 31) <> (iValue2 >> 31)) Then
         If value1 = value2 Then
            Return True
         End If           
         Return False
      End If

      Dim diff As Integer =  Math.Abs(iValue1 - iValue2)

      If diff <= units Then
         Return True
      End If

      Return False
   End Function
End Module
' The example displays the following output:
'       1 = 1.00000012: True

超出有案可稽的精度的浮点数的精度是特定于实现和.NET Framework 版本。The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of the .NET Framework. 因此,两个数字的比较可能会产生不同的结果,具体取决于.NET Framework 的版本,因为数字的内部表示形式的精度可能会更改。Consequently, a comparison of two numbers might produce different results depending on the version of the .NET Framework, because the precision of the numbers' internal representation might change.

调用方说明

编译器重载解析行为的两个明显的差异可能会考虑Equals(Object)方法重载。Compiler overload resolution may account for an apparent difference in the behavior of the two Equals(Object) method overloads. 如果之间的隐式转换obj自变量和一个Single定义和自变量类型不是Object,编译器可能会执行隐式转换和调用Equals(Single)方法。If an implicit conversion between the obj argument and a Single is defined and the argument is not typed as an Object, compilers may perform an implicit conversion and call the Equals(Single) method. 否则,调用方法Equals(Object)方法,它始终返回false如果其obj参数不是Single值。Otherwise, they call the Equals(Object) method, which always returns false if its obj argument is not a Single value. 下面的示例说明了两个方法重载之间的行为差异。The following example illustrates the difference in behavior between the two method overloads. 在除所有基元数值类型的情况下Double在 Visual Basic 和除DecimalDouble在 C# 中,第一次比较返回true因为编译器会自动执行扩大转换和调用Equals(Single)方法,而第二个比较返回false因为编译器将调用Equals(Object)方法。In the case of all primitive numeric types except for Double in Visual Basic and except for Decimal and Double in C#, the first comparison returns true because the compiler automatically performs a widening conversion and calls the Equals(Single) method, whereas the second comparison returns false because the compiler calls the Equals(Object) method.

[!code-csharpSystem.Single.Equals#2] [!code-vbSystem.Single.Equals#2][!code-csharpSystem.Single.Equals#2] [!code-vbSystem.Single.Equals#2]

另请参阅

适用于