/*
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.
*/
fun compareFloatArrays(a: FloatArray, b: FloatArray, tolerance: Float): Boolean {
// If lengths differ, arrays cannot be equal
if (a.size != b.size) return false
// Compare each element using absolute difference
for (i in a.indices) {
val diff: Float = kotlin.math.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
fun printComparison(result: Boolean) {
if (result) {
println("Arrays are equal within tolerance.")
} else {
println("Arrays differ.")
}
}
fun main() {
// Example arrays
val floatArr1: FloatArray = floatArrayOf(
12314.9872f,
3.14f,
12387.91371f,
8876.579013f
)
val floatArr2: FloatArray = floatArrayOf(
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.
*/