#include <stdio.h>
#include <math.h>
/*
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.
*/
// Compares two float arrays and returns 1 if all elements match within tolerance
int compareFloatArrays(
const float* a,
const float* b,
size_t length,
float tolerance
) {
// Loop through each element and compare using absolute difference
for (size_t i = 0; i < length; ++i) {
float diff = fabsf(a[i] - b[i]);
// If any element differs more than tolerance, arrays are not equal
if (diff > tolerance) {
return 0; // false
}
}
// All elements matched within tolerance
return 1; // true
}
// Prints the comparison result
void printComparison(int result) {
if (result) {
printf("Arrays are equal within tolerance.\n");
} else {
printf("Arrays differ.\n");
}
}
int main(void) {
// Example arrays
float floatArr1[] = {
12314.9872f,
3.14f,
12387.91372f,
8876.579013f
};
float floatArr2[] = {
12314.9872f,
3.14f,
12387.91371f,
8876.579013f
};
// Number of elements
size_t length = sizeof(floatArr1) / sizeof(floatArr1[0]);
// Tolerance chosen for comparison
float tolerance = 0.001f;
// Perform comparison
int result = compareFloatArrays(floatArr1, floatArr2, length, tolerance);
// Output result
printComparison(result);
return 0;
}
/*
run:
Arrays are equal within tolerance.
*/