How to compare two float arrays using a tolerance in Ruby

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
def compare_float_arrays(a, b, tolerance)
  # If lengths differ, arrays cannot be equal
  return false unless a.length == b.length

  # Compare each element using absolute difference
  a.zip(b).each do |x, y|
    diff = (x - y).abs

    # If any element differs more than tolerance, arrays are not equal
    return false if diff > tolerance
  end

  # All elements matched within tolerance
  true
end

# Prints the comparison result
def print_comparison(result)
  if result
    puts "Arrays are equal within tolerance."
  else
    puts "Arrays differ."
  end
end

# Example arrays
float_arr1 = [
  12314.9872,
  3.14,
  12387.91371,
  8876.579013
]

float_arr2 = [
  12314.9872,
  3.14,
  12387.91372,
  8876.579013
]

# Tolerance chosen for comparison
tolerance = 0.001

# Perform comparison
result = compare_float_arrays(float_arr1, float_arr2, tolerance)

# Output result
print_comparison(result)


#
# run:
#
# Arrays are equal within tolerance.
#

 



answered Sep 8 by avibootz
...