package main
import (
"fmt"
"math"
)
/*
Compare two float slices 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 slices and returns true if all elements match within tolerance
func compareFloatSlices(a []float64, b []float64, tolerance float64) bool {
// If lengths differ, slices cannot be equal
if len(a) != len(b) {
return false
}
// Compare each element using absolute difference
for i := 0; i < len(a); i++ {
diff := math.Abs(a[i] - b[i])
// If any element differs more than tolerance, slices are not equal
if diff > tolerance {
return false
}
}
// All elements matched within tolerance
return true
}
// Prints the comparison result
func printComparison(result bool) {
if result {
fmt.Println("Slices are equal within tolerance.")
} else {
fmt.Println("Slices differ.")
}
}
func main() {
// Example slices
floatSlice1 := []float64{
12314.9872,
3.14,
12387.91371,
8876.579013,
}
floatSlice2 := []float64{
12314.9872,
3.14,
12387.91372,
8876.579013,
}
// Tolerance chosen for comparison
tolerance := 0.001
// Perform comparison
result := compareFloatSlices(floatSlice1, floatSlice2, tolerance)
// Output result
printComparison(result)
}
/*
run:
Slices are equal within tolerance.
*/