Q (number Format) - Math Operations

Math Operations

Q numbers are a ratio of two integers: the numerator is kept in storage, the denominator is equal to 2n.

Consider the following example:

The Q8 denominator equals 28 = 256 1.5 equals 384/256 384 is stored, 256 is inferred because it is a Q8 number.

If the Q number's base is to be maintained (n remains constant) the Q number math operations must keep the denominator constant. The following formulas shows math operations on the general Q numbers and .

\begin{align}
\frac{N_1}{d} + \frac{N_2}{d} &= \frac{N_1+N_2}{d}\\
\frac{N_1}{d} - \frac{N_2}{d} &= \frac{N_1-N_2}{d}\\
\left(\frac{N_1}{d} \times \frac{N_2}{d}\right) \times d &= \frac{N_1\times N_2}{d}\\
\left(\frac{N_1}{d} / \frac{N_2}{d}\right)/d &= \frac{N_1/N_2}{d}
\end{align}

Because the denominator is a power of two the multiplication can be implemented as an arithmetic shift to the left and the division as an arithmetic shift to the right; on many processors shifts are faster than multiplication and division.

To maintain accuracy the intermediate multiplication and division results must be double precision and care must be taken in rounding the intermediate result before converting back to the desired Q number.

Using C the operations are (note that here, Q refers to the fractional part's number of bits) :

Read more about this topic:  Q (number Format)

Famous quotes containing the word operations:

    It may seem strange that any road through such a wilderness should be passable, even in winter, when the snow is three or four feet deep, but at that season, wherever lumbering operations are actively carried on, teams are continually passing on the single track, and it becomes as smooth almost as a railway.
    Henry David Thoreau (1817–1862)