How to compare two float lists using a tolerance in Python

1 Answer

0 votes
"""
Compare two float lists element-by-element using a tolerance.
Floating‑point values often differ slightly due to rounding,
so two numbers are considered "equal" when their absolute
difference is below the chosen threshold.
"""

from math import fabs

def compare_float_lists(a, b, tolerance):
    """
    Compare two float lists and return True if all elements
    match within the given tolerance.
    """

    # If lengths differ, lists cannot be equal
    if len(a) != len(b):
        return False

    # Compare each pair of elements using absolute difference
    for x, y in zip(a, b):
        diff = fabs(x - y)

        # If any element differs more than tolerance, lists are not equal
        if diff > tolerance:
            return False

    # All elements matched within tolerance
    return True


def print_comparison(result):
    """Prints the comparison result."""
    if result:
        print("Lists are equal within tolerance.")
    else:
        print("Lists differ.")


def main():
    # Example lists
    float_list1 = [
        12314.9872,
        3.14,
        12387.91372,
        8876.579013
    ]

    float_list2 = [
        12314.9872,
        3.14,
        12387.91371,
        8876.579013
    ]

    # Tolerance chosen for comparison
    tolerance = 0.001

    # Perform comparison
    result = compare_float_lists(float_list1, float_list2, tolerance)

    # Output result
    print_comparison(result)


if __name__ == "__main__":
    main()


"""
run:

Lists are equal within tolerance.

"""

 



answered Sep 8 by avibootz
edited Sep 8 by avibootz
...