Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,226 questions

56,128 answers

573 users

How to compare two float arrays using a tolerance in Pascal

1 Answer

0 votes
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.

*)

 



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