/*
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.
*/
object CompareFloatArraysWithTolerance {
// Compares two float arrays and returns true if all elements match within tolerance
def compareFloatArrays(a: Array[Float], b: Array[Float], tolerance: Float): Boolean = {
// If lengths differ, arrays cannot be equal
if (a.length != b.length) {
false
} else {
// Use zip + forall to avoid non-local returns and keep the logic clear
a.zip(b).forall { case (x, y) =>
val diff: Float = math.abs(x - y)
diff <= tolerance
}
}
}
// Prints the comparison result
def printComparison(result: Boolean): Unit = {
if (result)
println("Arrays are equal within tolerance.")
else
println("Arrays differ.")
}
def main(args: Array[String]): Unit = {
// Example arrays
val floatArr1: Array[Float] = Array(
12314.9872f,
3.14f,
12387.91371f,
8876.579013f
)
val floatArr2: Array[Float] = Array(
12314.9872f,
3.14f,
12387.91372f,
8876.579013f
)
// Tolerance chosen for comparison
val tolerance: Float = 0.001f
// Perform comparison
val result: Boolean = compareFloatArrays(floatArr1, floatArr2, tolerance)
// Output result
printComparison(result)
}
}
/*
run:
Arrays are equal within tolerance.
*/