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

56,142 answers

573 users

How to compare two float arrays for exact equality in Java

1 Answer

0 votes
/**
    Compare two float arrays element-by-element for exact equality.
    Floating‑point values must match exactly; even tiny rounding
    differences will cause inequality. This is stricter than using
    a tolerance-based comparison.
*/

public class CompareFloatArraysExact {

    /**
        Compares two float arrays and returns true only if all elements
        are exactly equal. Direct == comparison checks for exact binary equality.
    */
    public static boolean compareFloatArraysExact(float[] a, float[] b) {

        // If lengths differ, arrays cannot be equal
        if (a.length != b.length) {
            return false;
        }

        // Compare each element directly
        for (int i = 0; i < a.length; i++) {
            if (a[i] != b[i]) {
                return false;  // Found mismatch → arrays differ
            }
        }

        // All elements matched exactly
        return true;
    }

    /**
        Prints the comparison result.
    */
    public static void printComparison(boolean result) {
        if (result) {
            System.out.println("Arrays are exactly equal.");
        } else {
            System.out.println("Arrays differ.");
        }
    }

    public static void main(String[] args) {

        // Example arrays
        float[] floatArr1 = {
            12314.9872f,
            3.14f,
            12387.91834f,
            8873.579013f
        };

        float[] floatArr2 = {
            12314.9872f,
            3.14f,
            12387.91834f,
            8873.579013f
        };

        // Perform exact comparison
        boolean result = compareFloatArraysExact(floatArr1, floatArr2);

        // Output result
        printComparison(result);
    }
}


/*
run:

Arrays are exactly equal.

*/

 



answered Sep 9 by avibootz
...