How to compare two float arrays using a tolerance in PHP

1 Answer

0 votes
/*
    Compare two float arrays 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.
*/

/**
 * Compares two float arrays and returns true if all elements match within tolerance.
 */
function compareFloatArrays(array $a, array $b, float $tolerance): bool
{
    // If lengths differ, arrays cannot be equal
    if (count($a) !== count($b)) {
        return false;
    }

    // Compare each element using absolute difference
    for ($i = 0; $i < count($a); $i++) {
        $diff = abs($a[$i] - $b[$i]);

        // If any element differs more than tolerance, arrays are not equal
        if ($diff > $tolerance) {
            return false;
        }
    }

    // All elements matched within tolerance
    return true;
}

/**
 * Prints the comparison result.
 */
function printComparison(bool $result): void
{
    if ($result) {
        echo "Arrays are equal within tolerance.\n";
    } else {
        echo "Arrays differ.\n";
    }
}

// Example arrays
$floatArr1 = [
    12314.9872,
    3.14,
    12387.91372,
    8876.579013
];

$floatArr2 = [
    12314.9872,
    3.14,
    12387.91371,
    8876.579013
];

// Tolerance chosen for comparison
$tolerance = 0.001;

// Perform comparison
$result = compareFloatArrays($floatArr1, $floatArr2, $tolerance);

// Output result
printComparison($result);



/*
run:

Arrays are equal within tolerance.

*/

 



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