0

This is probably an old issue but I couldn't find anything satisfactory. I need to check if the result of a fp operation return zero minus all the weird fp behaviours. I tried this and failed miserably, help!

#include <iostream>
#include <cmath>
#include <limits>
#include <iomanip>
#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
    double d1 = 0.2;
    double d2 = 1.0;
    double d3 = 0.3;

    d1 = d1 + 0.1;
    d1 = d1 / d3;
    d1 = d1 - d2;

    // print d1 with max precision
    cout << std::setprecision(std::numeric_limits<double>::max_digits10) << d1 << endl;

    // accurately compare d1 with zero with regard to precision
    if (std::abs(d1) < std::numeric_limits<double>::epsilon())
    {
        cout << "d1 is zero" << endl;
    }
    else
    {
        cout << "d1 is not zero" << endl;
    }

    return 0;
}
273K
  • 29,503
  • 10
  • 41
  • 64
jmazzo
  • 37
  • 5
  • Check [`std::fpclassify`](https://en.cppreference.com/w/cpp/numeric/math/fpclassify) for being `FP_SUBNORMAL` or `FP_ZERO`. – Eljay Apr 23 '23 at 21:56
  • 6
    `std::numeric_limits::epsilon()` is the difference between 1.0 and the next representable value. It has nothing to do with the accuracy that your problem (whatever it may be) requires. If your calculation will produce results that are close to zero and you want to treat them as zero, decide, based on the details of your calculation, how close is close enough and test for that. This is not an easy thing to do; people get PhDs in how to handle floating-point math. You won't get sound answers from random folks on the Internet. – Pete Becker Apr 23 '23 at 22:11

0 Answers0