Skip to content

Commit 4293864

Browse files
authored
Fix IsApproximatelyEqual sample for negative values (#43345)
1 parent 3b77611 commit 4293864

File tree

1 file changed

+11
-2
lines changed
  • docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp

1 file changed

+11
-2
lines changed

docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison4.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,15 @@ public static void Main()
1111
one2 += .1f;
1212

1313
Console.WriteLine($"{one1:R} = {one2:R}: {one1.Equals(one2)}");
14-
Console.WriteLine($"{one1:R} is approximately equal to {one2:R}: {IsApproximatelyEqual(one1, one2, .000001f)}");
14+
Console.WriteLine($"{one1:R} is approximately equal to {one2:R}: " +
15+
$"{IsApproximatelyEqual(one1, one2, .000001f)}");
16+
17+
float negativeOne1 = -1 * one1;
18+
float negativeOne2 = -1 * one2;
19+
20+
Console.WriteLine($"{negativeOne1:R} = {negativeOne2:R}: {negativeOne1.Equals(negativeOne2)}");
21+
Console.WriteLine($"{negativeOne1:R} is approximately equal to {negativeOne2:R}: " +
22+
$"{IsApproximatelyEqual(negativeOne1, negativeOne2, .000001f)}");
1523
}
1624

1725
static bool IsApproximatelyEqual(float value1, float value2, float epsilon)
@@ -31,10 +39,11 @@ static bool IsApproximatelyEqual(float value1, float value2, float epsilon)
3139
if (divisor.Equals(0))
3240
divisor = Math.Min(value1, value2);
3341

34-
return Math.Abs(value1 - value2) / divisor <= epsilon;
42+
return Math.Abs((value1 - value2) / divisor) <= epsilon;
3543
}
3644
}
3745
// The example displays the following output:
3846
// 1 = 1.00000012: False
3947
// 1 is approximately equal to 1.00000012: True
48+
// -1 is approximately equal to -1.00000012: True
4049
// </Snippet12>

0 commit comments

Comments
 (0)