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,181 questions

56,073 answers

573 users

How to compare two float arrays using a tolerance in Go

1 Answer

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

*/

 



answered Sep 8 by avibootz
...