Skip to content

Example IsApproximatelyEqual has a bug when using negative numbers #9173

Closed
dotnet/docs
#43345
@robin-moss

Description

@robin-moss

The example code for IsApproximatelyEqual in single fails when you pass it negative numbers.

For example:

IsApproximatelyEqual(-10, -0.1)

returns True

This seems to be caused by the divisor being negative:

double divisor = Math.Max(value1.Value, value2.Value);
if (divisor.Equals(0))
{
    divisor = Math.Min(value1.Value, value2.Value);
}

return Math.Abs(value1.Value - value2.Value) / divisor <= epsilon;

Given two negative numbers the divisor is negative and so always <= epsilon. Testing locally a fix is to Math.Abs(divisor) or change the return line to:

return Math.Abs((value1.Value - value2.Value) / divisor) <= epsilon;

Metadata

Metadata

Assignees

No one assigned

    Labels

    Pri3Indicates issues/PRs that are low priorityarea-System.Runtimehelp wantedGood for community contributors to help [up-for-grabs]

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions