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 Kotlin

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.
*/

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.

*/

 



answered Sep 8 by avibootz
...