Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions src/libraries/System.Private.CoreLib/src/System/Half.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ namespace System

// Well-defined and commonly used values

public static Half Epsilon => new Half(EpsilonBits); // 5.9604645E-08
public static Half Epsilon => new Half(EpsilonBits); // 5.9604645E-08

public static Half PositiveInfinity => new Half(PositiveInfinityBits); // 1.0 / 0.0;

Expand Down Expand Up @@ -151,12 +151,19 @@ private ushort Significand

public static bool operator ==(Half left, Half right)
{
return left.Equals(right);
if (IsNaN(left) || IsNaN(right))
{
// IEEE defines that NaN is not equal to anything, including itself.
return false;
}

// IEEE defines that positive and negative zero are equivalent.
return (left._value == right._value) || AreZero(left, right);
}

public static bool operator !=(Half left, Half right)
{
return !(left.Equals(right));
return !(left == right);
}

/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
Expand Down Expand Up @@ -415,14 +422,11 @@ public override bool Equals(object? obj)
/// </summary>
public bool Equals(Half other)
{
if (IsNaN(this) || IsNaN(other))
if (this == other)
{
// IEEE defines that NaN is not equal to anything, including itself.
return false;
return true;
}

// IEEE defines that positive and negative zero are equivalent.
return (_value == other._value) || AreZero(this, other);
return IsNaN(this) && IsNaN(other);
}

/// <summary>
Expand Down
10 changes: 9 additions & 1 deletion src/libraries/System.Runtime/tests/System/HalfTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ public static IEnumerable<object[]> Equals_TestData()
yield return new object[] { Half.MaxValue, Half.MaxValue, true };
yield return new object[] { Half.MaxValue, Half.MinValue, false };
yield return new object[] { Half.MaxValue, UInt16BitsToHalf(0x0000), false };
yield return new object[] { Half.NaN, Half.NaN, false };
yield return new object[] { Half.NaN, Half.NaN, true };
yield return new object[] { Half.MaxValue, 789.0f, false };
yield return new object[] { Half.MaxValue, "789", false };
}
Expand Down Expand Up @@ -932,5 +932,13 @@ public static void ToSingle(Half half, float verify)
float f = (float)half;
Assert.Equal(f, verify, precision: 1);
}

[Fact]
public static void EqualityMethodAndOperator()
{
Assert.True(Half.NaN.Equals(Half.NaN));
Assert.False(Half.NaN == Half.NaN);
Assert.Equal(Half.NaN, Half.NaN);
}
}
}