How to compare two float vectors using a tolerance in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>

/*
    Compare two float vectors element-by-element using a tolerance.
    Floating-point values often differ slightly due to rounding,
    so we treat two numbers as "equal" when their absolute difference
    is below a chosen threshold.
*/

// Compares two float vectors and returns true if all elements match within tolerance
bool compareFloatVectors(
    const std::vector<float>& a,
    const std::vector<float>& b,
    float tolerance
) {
    // If sizes differ, vectors cannot be considered equal
    if (a.size() != b.size()) {
        return false;
    }

    // Use std::equal with a custom predicate for expressive comparison
    return std::equal(
        a.begin(),
        a.end(),
        b.begin(),
        [tolerance](float lhs, float rhs) {
            // Compare using absolute difference
                        
            return std::fabs(lhs - rhs) <= tolerance;
        }
    );
}

// Prints the comparison result
void printComparison(bool result) {
    if (result) {
        std::cout << "Vectors are equal within tolerance.\n";
    } else {
        std::cout << "Vectors differ.\n";
    }
}

int main() {
    // Example vectors
    std::vector<float> floatVec1{
        12314.9872f,
        3.14f,
        12387.91372f,
        8873.579013f
    };

    std::vector<float> floatVec2{
        12314.9872f,
        3.14f,
        12387.91371f,
        8873.579013f
    };

    // Tolerance chosen for this comparison
    float tolerance = 0.001f;

    // Perform comparison
    bool result = compareFloatVectors(floatVec1, floatVec2, tolerance);

    // Output result
    printComparison(result);
}


/*
run:

Vectors are equal within tolerance.

*/

 



answered Sep 8 by avibootz
edited Sep 8 by avibootz
...