How to Handle Negative Differences in C++?

December 27, 2025 2 answers
Asked by waiting_on_glue
I'm working on a C++ program where I calculate the difference between two double values and then compare that difference to a defined threshold (epsilon). Currently, if the difference is less than 0.001, I consider them equal. If it's within epsilon, it's close enough. However, I noticed that negative differences fall into my else statement, which isn't what I want. How can I manage negative differences in my logic? Here's the code I'm using: ```cpp #include #include using namespace std; int main() { double doubleA, doubleB, epsilon, actualDiff; cin >> doubleA >> doubleB >> epsilon; actualDiff = doubleB - doubleA; cout << "Difference: " << actualDiff << endl; cout << "Epsilon: " << epsilon << endl; if(actualDiff < 0.001) cout << "equal" << endl; else if (actualDiff <= epsilon) cout << "close enough" << endl; else cout << "not close" << endl; return 0; } ```

Answers

PATIO SHADE
You're on the right track! Instead of just doing a comparison on `actualDiff`, you can also utilize `std::fabs(actualDiff) < epsilon`. This checks the absolute difference against your epsilon. Itโ€™s widely used for comparing floating point numbers, and it will solve your issue with negative differences too!
Reply to this answer
tidal pool regular
To handle negative differences, you should use the absolute value function, `abs`. Instead of comparing `actualDiff` directly, you can check `abs(actualDiff)`. This way, you treat negative differences the same way as positive ones. A simple fix would be to replace your comparison with `if (abs(actualDiff) < 0.001)` for equality. It's a straightforward solution that fits well with your current logic!

waiting_on_glue: That makes sense! Thanks for the tip!

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions