Round numbers before (compare) statement
Scale by 100,000, round to a whole number and then compare.
No need to divide by the scaling and introduce more computational errors in order to compare.
#include <math.h>
int compare_rounded(double a, double b, double scale) {
// or use round(), nearby()
a = rint(a*scale);
b = rint(b*scale);
return (a > b) - (a < b);
}
OR perhaps more simply subtract. This gives slight different results. All depends what OP wants.
int compare_rounded2(double a, double b, double guard) {
double diff = a-b;
if (diff < -guard) return -1;
return diff > guard;
}
then call one of the 2
double s =d/a;
double s1 =d1/a1;
int cmp = compare_rounded(s1,s, 100000.0);
// or
int cmp = compare_rounded2(s1,s, 100000.0);
if (cmp > 0) {
puts("S1 > S");
} else if (cmp == 0) {
puts("S1 == S");
} else {
puts("S1 < S");
}
To cope with both numbers near the same limit of double
like DBL_MAX
, additional code is needed is the first function due to a*scale
overflow.