Q: How can I check if two floating point numbers are equal?
A: You can do something like this:
#define EPSILON 0.00000001
int compare(double num1, double num2, double error)
{
if(fabs(num1 - num2) < EPSILON)
return 1;
else
return 0;
}
Q: How can I check if two floating point numbers are equal with some acceptable error? Meaning, I have two numbers, a = 9.2
and b = 9.7
. When I set my error = 0.7
then I can consider a
and b
equal. (Its also true for a = 9.2
and b = 9.9
but false for a = 9.2
and b = 10.0
when the error
is 0.7
).
A: I tried this but every time (no matter how error
look like), it always shows 0
:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define EPSILON 0.00000001
static int compare(double num1, double num2, double error)
{
if((fabs(num1 - num2) < EPSILON - error) || (fabs(num1 - num2 + error) < EPSILON + error))
return 1;
else
return 0;
}
static int areEqual(const double *x, int size, double error)
{
int i;
for (i = 0; i < size - 1; i++)
if (!compare(x[i], x[i + 1], error))
return 0;
return 1;
}
int main(int argc, char **argv)
{
double tab[] = {9.2, 9.7, 9.3, 9.6, 9.4, 10.0, 9.1, 9.7};
double error = 0.9;
const int N = 10;
printf("%d\n", areEqual(tab, N, error));
return 0;
}
Tried also do it this way:
static int compare2(double num1, double num2, double error)
{
if(fabs(num1 - num2) <= error)
return 1;
else
return 0;
}
But shows 0
too.
EDIT:
Finally, did it! Working code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#define EPSILON 0.00000001
static void checkFabs()
{
printf("%d\n", fabs(-0.7) < 1.0);
printf("%d\n", fabs(-0.75) < 1.0);
printf("%d\n", fabs(-0.71) < 1.0);
printf("%d\n", fabs(0.5) < 0.9);
printf("%d\n", fabs(0.6) < 0.9);
printf("%d\n", fabs(0.3) < 0.9);
printf("%d\n", fabs(0.2) < 0.9);
printf("%d\n", fabs(0.8) < 0.9);
printf("%d\n", fabs(0.1) < 0.9);
printf("%d\n", fabs(0.9) <= 0.9);
}
static int compare(double num1, double num2, double error)
{
if(fabs(num1-num2) <= error + EPSILON)
return 1;
else
return 0;
}
static int areEqual(const double *x, int size, double error)
{
int i;
for (i = 0; i < size - 1; i++)
if (!compare(x[i], x[i + 1], error))
return 0;
return 1;
}
int main(int argc, char **argv)
{
double tab[] = {9.2, 9.7, 9.3, 9.6, 9.4, 9.9, 9.1, 9.7};
double error = 0.9;
const int N = 8;
printf("%d\n", areEqual(tab, N, error));
return 0;
}
There are 8 elements in your array, not 10. Here is the compare function that you need: