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

Misleading example for QPoint[F]::dotProduct()

    XMLWordPrintable

Details

    • 371516653982fe6672fff3d294b2742c60ea9183 (qt/qtbase/dev)
    • Team 1 Foundation_Sprint 44

    Description

      Problem

      The example code for QPoint::dotProduct() and QPointF::dotProduct() is as follows:

      QPoint p( 3, 7);
      QPoint q(-1, 4);
      int lengthSquared = QPoint::dotProduct(p, q);   // lengthSquared becomes 25
      

      The name "lengthSquared" is definitively wrong. In this special case, the result (25) is actually the squared distance between the two points. But in generic cases, dotProduct() returns the dot product of the two points interpreted as 2-element vectors.

      The dot product of two 2-element vectors is defined as follows (source code of QPointF::dotProduct()):

      return p1.xp * p2.xp + p1.yp * p2.yp;
      

      As easily seen, the result is negative in 50% of all cases. This can not be a squared distance.

      Suggestion

      The dot product's most popular property is that it is equal to zero if the two vectors are perpendicular. So I suggest to replace the example code by the following:

      QPoint p( 3, 7);
      QPoint q(-1, 4);
      if (QPoint::dotProduct(p, q) == 0) {
          qDebug() << "Vectors p and q are perpendicular! (Or one of them is null.)";
      } else {
          qDebug() << "Vectors p and q are not perpendicular.";
      }
      

      Or simply by this:

      QPoint p( 3, 7);
      QPoint q(-1, 4);
      int dotProduct = QPoint::dotProduct(p, q);
      // Equivalent to int dotProduct = p.x() * q.x() + p.y() * q.y()
      

      Attachments

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

        Activity

          People

            ievgenii.meshcheriakov Ievgenii Meshcheriakov
            checkedtrashcan David Hurka
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Gerrit Reviews

                There are no open Gerrit changes