Skip to content

Сomparing large numbers doesn't work #181

@partizanes

Description

@partizanes

python3.8, python3.9

Test code:

from dictdiffer import diff

dict1 = dict({'test': {'serial_number': 22570409781991170591038650551}})
dict2 = dict({'test': {'serial_number': 22570409781991170591038650552}})
print(list(diff(dict1, dict2)))

Return empty list.

The problem was using math.isclose which produces false results:

def are_different(first, second, tolerance, absolute_tolerance=None):
    """Check if 2 values are different.

    In case of numerical values, the tolerance is used to check if the values
    are different.
    In all other cases, the difference is straight forward.
    """
    if first == second:
        # values are same - simple case
        return False

    first_is_nan, second_is_nan = bool(first != first), bool(second != second)

    if first_is_nan or second_is_nan:
        # two 'NaN' values are not different (see issue #114)
        return not (first_is_nan and second_is_nan)
    elif isinstance(first, num_types) and isinstance(second, num_types):
        # two numerical values are compared with tolerance
        return not math.isclose(
            first,
            second,
            rel_tol=tolerance or 0,
            abs_tol=absolute_tolerance or 0,
        )
    # we got different values
    return True

Test example:

import math  

print(math.isclose(22570409781991170591038650551, 22570409781991170591038650552, rel_tol=0.0, abs_tol=0.0)) # TRUE
print(22570409781991170591038650551 == 22570409781991170591038650552)                                       # FALSE

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions