Single.Equals Method (Object)
Returns a value indicating whether this instance is equal to a specified object.
Assembly: mscorlib (in mscorlib.dll)
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. The following example reports that the Single value .3333 and the Single returned by dividing 1 by 3 are unequal.
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. 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.");
In this case, the values are equal.
The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of the .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.
.NET FrameworkSupported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0
.NET Framework Client ProfileSupported in: 4, 3.5 SP1
Portable Class LibrarySupported in: Portable Class Library
.NET for Windows Store appsSupported in: Windows 8
.NET for Windows Phone appsSupported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8
Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.