program CompareFloatArraysWithTolerance;
{$mode objfpc}{$H+}
(*
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.
*)
uses
Math; // Provides Abs() and other math utilities
// Compares two float arrays and returns True if all elements match within tolerance
function CompareFloatArrays(
const A, B: array of Single;
Tolerance: Single
): Boolean;
var
i: Integer;
diff: Single;
begin
// If lengths differ, arrays cannot be equal
if Length(A) <> Length(B) then
Exit(False);
// Compare each element using absolute difference
for i := 0 to High(A) do
begin
diff := Abs(A[i] - B[i]);
// If any element differs more than tolerance, arrays are not equal
if diff > Tolerance then
Exit(False);
end;
// All elements matched within tolerance
Result := True;
end;
// Prints the comparison result
procedure PrintComparison(ResultValue: Boolean);
begin
if ResultValue then
WriteLn('Arrays are equal within tolerance.')
else
WriteLn('Arrays differ.');
end;
var
floatArr1: array of Single;
floatArr2: array of Single;
tolerance: Single;
result: Boolean;
begin
// 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);
end.
(*
run:
Arrays are equal within tolerance.
*)