[math] Floating point equality with relative epsilon comparisons
This commit is contained in:
29
src/float_utils.c
Normal file
29
src/float_utils.c
Normal file
@@ -0,0 +1,29 @@
|
||||
#include "float_utils.h"
|
||||
|
||||
inline bool float_equals_epsilon(float a, float b, float epsilon) {
|
||||
float diff = fabsf(a - b);
|
||||
a = fabsf(a);
|
||||
b = fabsf(b);
|
||||
|
||||
float largest = (b > a) ? b : a;
|
||||
|
||||
return (diff <= largest * epsilon);
|
||||
}
|
||||
|
||||
inline bool float_equals(float a, float b) {
|
||||
return float_equals_epsilon(a, b, FLT_EPSILON);
|
||||
}
|
||||
|
||||
inline bool double_equals_epsilon(double a, double b, double epsilon) {
|
||||
double diff = fabs(a - b);
|
||||
a = fabs(a);
|
||||
b = fabs(b);
|
||||
|
||||
double largest = (b > a) ? b : a;
|
||||
|
||||
return (diff <= largest * epsilon);
|
||||
}
|
||||
|
||||
inline bool double_equals(double a, double b) {
|
||||
return double_equals_epsilon(a, b, DBL_EPSILON);
|
||||
}
|
||||
16
src/float_utils.h
Normal file
16
src/float_utils.h
Normal file
@@ -0,0 +1,16 @@
|
||||
#ifndef FLOAT_UTILS_H
|
||||
#define FLOAT_UTILS_H
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
#include <float.h>
|
||||
#include <math.h>
|
||||
|
||||
bool float_equals(float a, float b);
|
||||
bool float_equals_epsilon(float a, float b, float epsilon);
|
||||
|
||||
bool double_equals(double a, double b);
|
||||
bool double_equals_epsilon(double a, double b, double epsilon);
|
||||
|
||||
#endif
|
||||
|
||||
Reference in New Issue
Block a user