Reputation: 55
I'm working on some old C code that checks if two doubles are relatively equal. It works most of the time but sometimes it says the 2 doubles aren't equal even though the Print statement shows they are equal. I assume there must be a very small difference that the print statement is not showing.
Here is the C code I'm working on. I was thinking I need to use a floor function that uses the precision value?
I'm sure there is a better way to do this in C++ but I have to keep it C based.
Any help would be much appreciated. TIA
// example function input
// double amount1 = 0.00015; double precision1 = 0.00001;
// double amount2 = 0.00015; double precision2 = 0.00001;
bool amountsEqual(const double amount1, const double precision1, const double amount2, const double precision2) {
double amount = 0;
if (amount1 > amount2) {
amount = amount1 - amount2;
}
else if (amount1 < amount2) {
amount = amount2 - amount1;
}
else {
return true;
}
double precision = 0;
if (precision1 <= precision2) {
precision = precision1;
}
else {
precision = precision2;
}
if (amount <= precision)
return true;
printf("amount1: %lf amount2: %lf / precision1: %lf precision2: %lf / amount: %lf precision: %lf\n", amount1, amount2, precision1, precision2, amount, precision);
return false;
}
Upvotes: 0
Views: 62