0

In the program I used the assert statement to compare the matrices and operators are implemented using function overloading.

Below is the part of code of assert-

Mat2x2  m1(2.5, 3.6, 8.7, 5.8); 
Mat2x2  t1 = m1;
    ++m1;                                          // ++Mat2x2 
    assert(m1 == t1 + 1);
    --m1;                                          // --Mat2x2         
    assert(m1 == t1);

Below is the code of operator overloading of "==" operator-

bool operator==(const Mat2x2& m1, const Mat2x2& m2) 
{
    return ((m1[0] == m2[0]) && (m1[1] == m2[1]) && (m1[2] == m2[2]) && (m1[3] == m2[3]));
}

Below is the code of operator overloading of "++" and "--" operator-

Mat2x2& Mat2x2::operator++() {
    *this += 1;
    return *this;
}

Mat2x2& Mat2x2::operator--() {
    *this -= 1;
    return *this;
}

While i am printing the value of m1 and t1, it seems to be same and also have the same data type. The result is below-

m1: [2.50 , 3.60 , 8.70 , 5.80]

t1: [2.50 , 3.60 , 8.70 , 5.80]

Assertion failed: m1 == t1

Values seems to be same, still the assertion is failed.

How can i remove this error

coder
  • 37
  • 5
  • `assert(m1 == t1);` has failed. It's the one after `--m1`. You should be comparing it with `assert(m1 == t1 - 1);`, no? – Zoso Jul 18 '21 at 02:36
  • No, earlier i did ++m, so after --m1 it should be same as m. – coder Jul 18 '21 at 02:50
  • Ah, my bad. Do you have issues sharing a simplified `Mat2x2` implementation with all the operator overloads? What's `operator[]`? Also is `operator ==` a free function? – Zoso Jul 18 '21 at 02:54
  • const double& Mat2x2::operator[](int index) const { if (index < 0 || index >= 4) { throw invalid_argument("invalid argument"); } return entries[index]; } – coder Jul 18 '21 at 02:58
  • Above is the overloading of "[]" operator and same has been used for non const method – coder Jul 18 '21 at 02:58
  • Yesss operator == is a free function – coder Jul 18 '21 at 02:59
  • 1
    Likely a duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). Taking a floating point value, adding 1 and then subtracting 1 doesn't necessarily produce the exact original value, due to finite precision and rounding. – Igor Tandetnik Jul 18 '21 at 03:45
  • @IgorTandetnik I'd thought of that and tried something like [this](https://godbolt.org/z/evjnK75s7) but it didn't reproduce the issue. – Zoso Jul 18 '21 at 03:52
  • One thing I could suggest to be tried is that you can investigate the `operator==` function and check which equality fails. I wasn't able to replicate the issue but maybe it's specific to your setup. – Zoso Jul 18 '21 at 04:33

0 Answers0