Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@ public static void Main()
one2 += .1f;

Console.WriteLine($"{one1:R} = {one2:R}: {one1.Equals(one2)}");
Console.WriteLine($"{one1:R} is approximately equal to {one2:R}: {IsApproximatelyEqual(one1, one2, .000001f)}");
Console.WriteLine($"{one1:R} is approximately equal to {one2:R}: " +
$"{IsApproximatelyEqual(one1, one2, .000001f)}");

float negativeOne1 = -1 * one1;
float negativeOne2 = -1 * one2;

Console.WriteLine($"{negativeOne1:R} = {negativeOne2:R}: {negativeOne1.Equals(negativeOne2)}");
Console.WriteLine($"{negativeOne1:R} is approximately equal to {negativeOne2:R}: " +
$"{IsApproximatelyEqual(negativeOne1, negativeOne2, .000001f)}");
}

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

return Math.Abs(value1 - value2) / divisor <= epsilon;
return Math.Abs((value1 - value2) / divisor) <= epsilon;
}
}
// The example displays the following output:
// 1 = 1.00000012: False
// 1 is approximately equal to 1.00000012: True
// -1 is approximately equal to -1.00000012: True
// </Snippet12>