Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-26453

Floating point exceptions mishandled by qFuzzyCompare

    XMLWordPrintable

Details

    Description

      qFuzzyCompare assumes that the control word for the floating point hardware is set to avoid exceptions. For programs with significant floating point calculations such as engineering or statistical apps, exceptions are usually turned on. However, if the exceptions are turned on, the program will crash.

      Many of the UI functions seem to use qFuzzyCompare; specifically QtextDocument is the first to crash in my code.

      The offending code is:

      Q_DECL_CONSTEXPR static inline bool qFuzzyCompare(double p1, double p2)
      {
          return (qAbs(p1 - p2) <= 0.000000000001 * qMin(qAbs(p1), qAbs(p2)));
      }
      

      which causes underflow.

      If such a compare is necessary, please modify the control word before use, then return it to the previous setting as in:

      Q_DECL_CONSTEXPR static bool qFuzzyCompare(double p1, double p2)
      {
          int err;
          unsigned int control_word;
          unsigned int old_control_word;
          _clearfp();
          err = _controlfp_s(&old_control_word, 0, 0);  // get old control word
          err = _controlfp_s(&control_word, _MCW_EM, _MCW_EM);  // turn off exceptions
          bool compare = (qAbs(p1 - p2) <= 0.000000000001 * qMin(qAbs(p1), qAbs(p2)));
          _clearfp();
          err = _controlfp_s(&control_word, old_control_word, _MCW_EM); // restore old control word
          // handle err if necessary
          return compare;
      }
      

      This needs to be used wherever the floating point control exceptions are assumed to be off. It is a requirement for all drivers to save and restore the control word; why not interface code?

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            laknoll Lars Knoll
            moose John Mauer
            Votes:
            0 Vote for this issue
            Watchers:
            8 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Gerrit Reviews

                There are no open Gerrit changes