Example: Use Equality and Inequality Operators

The functions is_equal and is_not_equal in the following example provide a reliable comparison between two complex values:

   // Testing complex values for equality within a certain tolerance
   #include <complex.h>
   #include <iostream.h>            // for output
   #include <iomanip.h>             // for use of setw() manipulator
   int is_equal(const complex &a, const complex &b,
                const double tol=0.0001)
   {
      return (abs(real(a) - real(b)) < tol &&
              abs(imag(a) - imag(b)) < tol);
   }
   int is_not_equal(const complex &a, const complex &b,
                    const double tol=0.0001)
   {
      return !is_equal(a, b, tol);
   }
   int main(int argc, char *argv[])
   {
       complex c[4] = { complex(1.0, 2.0),
                       complex(1.0, 2.0),
                       complex(3.0, 4.0),
                       complex(1.0000163,1.999903581)};
      cout << “Comparison of array elements c[0] to c[3]\n”
           << “== means identical,\n!= means unequal,\n”
           << “ ~ means equal within tolerance of 0.0001.\n\n”
           << setw(10) << “Element”
           << setw(6) << 0
           << setw(6) << 1
           << setw(6) << 2
           << setw(6) << 3
           << endl;
      for (int i=0;i<4;i++) {
         cout << setw(10) << i;
         for (int j=0;j<4;j++) {
            if (c[i]==c[j]) cout << setw(6) << “==”;
            else if (is_equal(c[i],c[j])) cout << setw(6) << “~”;
                else if (is_not_equal(c[i],c[j])) cout << setw(6) << “!=”;
               else cout << setw(6) << “???”;
            }
         cout << endl;
         }
      return 0
      }

This example produces the following output:

   Comparison of array elements c[0] to c[3]
   == means identical,
   != means unequal,
    ~ means equal within tolerance of 0.0001.

      Element     0     1     2     3
            0    ==    ==    !=     ~
            1    ==    ==    !=     ~
            2    !=    !=    ==    !=
            3     ~     ~    !=    ==

Related Concepts

Related Tasks