Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++

Fixed-Point Arithmetic Types for C++


The rounding integer implementation considers an integer as a binary fixed-point number with no bits to the right of the radix point. Integer addition, subtraction, and multiplication produce exact results. They are implemented using the arithmetic operations for the underlying integral type.

Integer division truncates toward zero. To round the result of integer division, the code takes advantage of the C++ modulus (%) operator. The value of a%b is the integer remainder of the expression a/b. If the remainder is greater than or equal to half the divisor, the quotient is rounded up by adding 1. Rather than divide the divisor by 2 (reintroducing the undesirable truncation), I double the remainder (using multiplication, which has an exact result) and compare it to the divisor.

assert(n >= 0 && d > 0);
q = n / d;
r = n % d;
if ((r<<1) >= d) q += 1;

The integer division instruction on most processors produces both a quotient and a remainder. The Visual C++ optimizer efficiently reuses the already-computed remainder instead of recomputing it. On more modest hardware, or less-optimizing compilers, the Standard C runtime function ldiv() can be used to produce a structure containing both quotient and remainder. ldiv() is not an intrinsic function in VC7, so it has a high performance cost.

The signs of the operands present a further challenge in rounding. The signs of the quotient and remainder depend on the signs of the divisor and dividend. Handling all four cases of operand signs generates some code bloat, but not much speed penalty. I have verified this code on Intel-architecture processors. Other processors implement the sign of the remainder differently, so users of this template should verify its correctness with their processor.

I investigated a branch-free rounding computation to improve performance, but there was no observable improvement on the PC. The branch-free code is compact, but was difficult to construct. Listing Two shows the division code with rounding.

Listing Two

// Listing2.h: scaled multiplication and rounded division
template <typename T> inline T scaled_multiplication(T a, T b, int s)
{
     T p = rounded_division(a * b, (T)s);
     return p;
}// end rounded_multiplication

template <typename T> inline T rounded_division(T n, T d)
{
     T q = n / d;
     T r = n % d;

#     if defined BRANCH_FREE
          q += sign(n^d) & neg(abs(d) - (abs(r)<<1) - 1);
#     elif defined NO_ROUNDING
#     else
          if (n < 0)
               if (d < 0)
               {// num -, den -, quot +, rem -
                    if ((r << 1) < d)
                         ++q;
               }
               else // d >= 0)
               {// num -, den +, quot -, rem -
                    if ((-r << 1) > d)
                         --q;
               }
          else // n >= 0
               if (d < 0)
               {// num +, den -, quot -, rem +
                    if ((-r << 1) < d)
                         --q;
               }
               else // d >= 0
               {// num +, den +, quot +, rem +
                    if ((r << 1) > d)
                         ++q;
               }
#     endif
     return q;
} // end rounded_division


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.