Document number: LEWG, EWG, SG14, SG6: P0037R0
Date: 2015-09-28
Project: Programming Language C++, Library Evolution WG, SG14
Reply-to: John McFarlane, fixed-point@john.mcfarlane.name
This proposal introduces a system for performing binary fixed-point arithmetic using built-in integral types.
Floating-point types are an exceedingly versatile and widely supported method of expressing real numbers on modern architectures.
However, there are certain situations where fixed-point arithmetic is preferable. Some systems lack native floating-point registers and must emulate them in software. Many others are capable of performing some or all operations more efficiently using integer arithmetic. Certain applications can suffer from the variability in precision which comes from a dynamic radix point [1]. In situations where a variable exponent is not desired, it takes valuable space away from the significand and reduces precision.
Built-in integer types provide the basis for an efficient representation of binary fixed-point real numbers. However, laborious, error-prone steps are required to normalize the results of certain operations and to convert to and from fixed-point types.
A set of tools for defining and manipulating fixed-point types is proposed. These tools are designed to make work easier for those who traditionally use integers to perform low-level, high-performance fixed-point computation.
This proposal is a pure library extension. It does not require changes to any standard classes, functions or headers.
The design is driven by the following aims in roughly descending order:
Fixed-point numbers are specializations of
where the template parameters are described as follows.
ReprType
Type Template ParameterThis parameter identifies the capacity and signedness of the
underlying type used to represent the value. In other words, the size
of the resulting type will be sizeof(ReprType)
and it will be
signed iff is_signed<ReprType>::value
is true. The default is
int
.
ReprType
must be a fundamental integral type and should not be the
largest size. Suitable types include: std::int8_t
, std::uint8_t
,
std::int16_t
, std::uint16_t
, std::int32_t
and std::uint32_t
.
In limited situations, std::int64_t
and std::uint64_t
can be used.
The reasons for these limitations relate to the difficulty in finding
a type that is suitable for performing lossless integer
multiplication.
Exponent
Non-Type Template ParameterThe exponent of a fixed-point type is the equivalent of the exponent
field in a floating-point type and shifts the stored value by the
requisite number of bits necessary to produce the desired range. The
default value of Exponent
is zero, giving fixed_point<T>
the same
range as T
.
The resolution of a specialization of fixed_point
is
and the minimum and maximum values are
and
respectively.
Any usage that results in values of Exponent
which lie outside the
range, (INT_MIN / 2
, INT_MAX / 2
), may result in undefined
behavior and/or overflow or underflow. This range of exponent values
is far in excess of the largest built-in floting-point type and should
be adequate for all intents and purposes.
make_fixed
and make_ufixed
Helper TypeThe Exponent
template parameter is versatile and concise. It is an
intuitive scale to use when considering the full range of positive and
negative exponents a fixed-point type might possess. It also
corresponds to the exponent field of built-in floating-point types.
However, most fixed-point formats can be described more intuitively by the cardinal number of integer and/or fractional digits they contain. Most users will prefer to distinguish fixed-point types using these parameters.
For this reason, two aliases are defined in the style of
make_signed
.
These aliases are declared as:
and
They resolve to a fixed_point
specialization with the given
signedness and number of integer and fractional digits. They may
contain additional integer and fractional digits.
For example, one could define and initialize an 8-bit, unsigned, fixed-point variable with four integer digits and four fractional digits:
or a 32-bit, signed, fixed-point number with two integer digits and 29 fractional digits:
Fixed-point numbers can be explicitly converted to and from built-in arithmetic types.
While effort is made to ensure that significant digits are not lost
during conversion, no effort is made to avoid rounding errors.
Whatever would happen when converting to and from an integer type
largely applies to fixed_point
objects also. For example:
...equates to true
and is considered a acceptable rounding error.
Any operators that might be applied to integer types can also be applied to fixed-point types. A guiding principle of operator overloads is that they perform as little run-time computation as is practically possible.
With the exception of shift and comparison operators, binary operators can take any combination of:
is_arithmetic
is true.Where the inputs are not identical fixed-point types, a simple set of promotion-like rules are applied to determine the return type:
Some examples:
The reasoning behind this choice is a combination of predictability and performance. It is explained for each rule as follows:
Shift operator overloads require an integer type as the right-hand parameter and return a type which is adjusted to accommodate the new value without risk of overflow or underflow.
Comparison operators convert the inputs to a common result type
following the rules above before performing a comparison and returning
true
or false
.
Because arithmetic operators return a result of equal capacity to their inputs, they carry a risk of overflow. For instance,
causes overflow because because a type with 4 integer bits cannot store a value of 16.
Overflow of any bits in a signed or unsigned fixed-point type is classed as undefined behavior. This is a minor deviation from built-in integer arithmetic where only signed overflow results in undefined behavior.
The other typical cause of lost bits is underflow where, for example,
results in a value of 7. This results in loss of precision but is generally considered acceptable.
However, when all bits are lost due to underflow, the value is said to be flushed and this is classed as undefined behavior.
Errors resulting from overflow and flushes are two of the biggest headaches related to fixed-point arithmetic. Integers suffer the same kinds of errors but are somewhat easier to reason about as they lack fractional digits. Floating-point numbers are largely shielded from these errors by their variable exponent and implicit bit.
Three strategies for avoiding overflow in fixed-point types are presented:
For arithmetic operators, choice 1) is taken because it most closely follows the behavior of integer types. Thus it should cause the least surprise to the fewest users. This makes it far easier to reason about in code where functions are written with a particular type in mind. It also requires the least computation in most cases.
Choices 2) and 3) are more robust to overflow events. However, they represent different trade-offs and neither one is the best fit in all situations. For these reasons, they are presented as named functions.
Function template, promote
, borrows a term from the language
feature which avoids integer overflow prior to certain operations. It
takes a fixed_point
object and returns the same value represented
by a larger fixed_point
specialization.
For example,
is equivalent to
Complimentary function template, demote
, reverses the process,
returning a value of a smaller type.
The following named function templates can be used as a hassle-free alternative to arithmetic operators in situations where the aim is to avoid overflow.
Unary functions:
Binary functions:
Some notes:
trunc_
functions return the result as a type no larger than
the inputs and with an exponent adjusted to avoid overflow;promote_
functions return the result as a type large enough
to avoid overflow and underflow;_multiply
and _square
functions are not guaranteed to be
available for 64-bit types;_multiply
and _square
functions produce undefined behavior
when all input parameters are the most negative number;_square
functions return an unsigned type;_add
, _subtract
, _multiply
and _divide
functions take
heterogeneous fixed_point
specializations;_divide
and _reciprocal
functions in no way guard against
divide-by-zero errors;trunc_shift_
functions return results of the same type as
their first input parameter andThe following example calculates the magnitude of a 3-dimensional vector.
Calling the above function as follows
returns the value, 9.890625.
fixed_point<>
Class TemplateBecause the aim is to provide an alternative to existing arithmetic types which are supported by the standard library, it is conceivable that a future proposal might specialize existing class templates and overload existing functions.
Possible candidates for overloading include the functions defined in
\numeric_limits
. A new type
trait, is_fixed_point
, would also be useful.
While fixed_point
is intended to provide drop-in replacements to
existing built-ins, it may be preferable to deviate slightly from the
behavior of certain standard functions. For example, overloads of
functions from \errno
in the case of an error
prevents a function from being defined as pure. This highlights a
wider issue surrounding the adoption of the functional approach and
compile-time computation that is beyond the scope of this document.
The reason that ReprType
is restricted to built-in integer types
is that a number of features require the use of a higher - or
lower-capacity type. Supporting alias templates are defined to
provide fixed_point
with the means to invoke integer types of
specific capacity and signedness at compile time.
There is no general purpose way of deducing a higher or
lower-capacity type given a source type in the same manner as
make_signed
and make_unsigned
. If there were, this might be
adequate to allow alternative choices for ReprType
.
The bounded::integer library [2] exemplifies the benefits of keeping track of ranges of values in arithmetic types at compile time.
To a limited extent, the trunc_
functions defined here also keep
track of - and modify - the limits of values. However, a combination
of techniques is capable of producing superior results.
For instance, consider the following expression:
The type of n
is make_ufixed<8, 0>
but its value does not
exceed 81. Hence, an integer bit has been wasted. It may be possible
to track more accurate limits in the same manner as the
bounded::integer library in order to improve the precision of types
returned by trunc_
functions. For this reason, the exact value of
the exponents of these return types is not given.
Notes:
The behavior of the types specialized from fixed_point
represent
one sub-set of all potentially desirable behaviors. Alternative
characteristics include:
trunc_
or promote_
behavior;One way to extend fixed_point
to cover these alternatives would be
to add non-type template parameters containing bit flags or enumerated
types. The default set of values would reflect fixed_point
as it
stands currently.
Many examples of fixed-point support in C and C++ exist. While almost all of them aim for low run-time cost and expressive alternatives to raw integer manipulation, they vary greatly in detail and in terms of their interface.
One especially interesting dichotomy is between solutions which offer a discrete selection of fixed-point types and libraries which contain a continuous range of exponents through type parameterization.
One example of the former is found in proposal N1169 [5], the intent of which is to expose features found in certain embedded hardware. It introduces a succinct set of language-level fixed-point types and impose constraints on the number of integer or fractional digits each can possess.
As with all examples of discrete-type fixed-point support, the limited choice of exponents is a considerable restriction on the versatility and expressiveness of the API.
Nevertheless, it may be possible to harness performance gains provided by N1169 fixed-point types through explicit template specialization. This is likely to be a valuable proposition to potential users of the library who find themselves targeting platforms which support fixed-point arithmetic at the hardware level.
There are many other C++ libraries available which fall into the latter category of continuous-range fixed-point arithmetic [3] [6] [7]. In particular, an existing library proposal, N3352 [8], aims to achieve very similar goals through similar means and warrants closer comparison than N1169.
N3352 introduces four class templates covering the quadrant of signed versus unsigned and fractional versus integer numeric types. It is intended to replace built-in types in a wide variety of situations and accordingly, is highly compile-time configurable in terms of how rounding and overflow are handled. Parameters to these four class templates include the storage in bits and - for fractional types - the resolution.
The fixed_point
class template could probably - with a few caveats -
be generated using the two fractional types, nonnegative
and
negatable
, replacing the ReprType
parameter with the integer bit
count of ReprType
, specifying fastest
for the rounding mode and
specifying undefined
as the overflow mode.
However, fixed_point more closely and concisely caters to the needs of users who already use integer types and simply desire a more concise, less error-prone form. It more closely follows the four design aims of the library and - it can be argued - more closely follows the spirit of the standard in its pursuit of zero-cost abstraction.
Some aspects of the design of the N3352 API which back up these conclusion are that:
trunc_
function templates and are potentially more costly at run-time;The added versatility that the N3352 API provides regarding rounding and overflow handling are of relatively low priority to users who already bear the scars of battles with raw integer types. Nevertheless, providing them as options to be turned on or off at compile time is an ideal way to leave the choice in the hands of the user.
Many high-performance applications - in which fixed-point is of potential value - favor run-time checks during development which are subsequently deactivated in production builds. The N3352 interface is highly conducive to this style of development. It is an aim of the fixed_point design to be similarly extensible in future revisions.
Subgroup: Guy Davidson, Michael Wong
Contributors: Ed Ainsley, Billy Baker, Lance Dyson, Marco Foco,
Clément Grégoire, Nicolas Guillemot, Matt Kinzelman, Joël Lamotte,
Sean Middleditch, Patrice Roy, Peter Schregle, Ryhor Spivak
An in-development implementation of the fixed_point class template and
its essential supporting functions and types is available
[9]. It includes a
utility header containing such things as math and trigonometric
functions and a partial numeric_limits
specialization. Compile-time
and run-time tests are included as well as benchmarking support. It is
the source of examples and measurements cited here.
Despite a focus on usable interface and direct translation from integer-based fixed-point operations, there is an overwhelming expectation that the source code result in minimal instructions and clock cycles. A few preliminary numbers are presented to give a very early idea of how the API might perform.
Some notes:
Figures were taken from a single CPU, OS and compiler, namely:
Fixed inputs were provided to each function, meaning that branch prediction rarely fails. Results may also not represent the full range of inputs.
Where applicable various combinations of integer, floating-point and fixed-point types were tested with the following identifiers:
uint8_t
, int8_t
, uint16_t
, int16_t
, uint32_t
, int32_t
,
uint64_t
and int64_t
built-in integer types;float
, double
and long double
built-in floating-point types;Plus, minus, multiplication and division were tested in isolation using a number of different numeric types with the following results:
name cpu_time
add(float) 1.78011
add(double) 1.73966
add(long double) 3.46011
add(u4_4) 1.87726
add(s3_4) 1.85051
add(u8_8) 1.85417
add(s7_8) 1.82057
add(u16_16) 1.94194
add(s15_16) 1.93463
add(u32_32) 1.94674
add(s31_32) 1.94446
add(int8_t) 2.14857
add(uint8_t) 2.12571
add(int16_t) 1.9936
add(uint16_t) 1.88229
add(int32_t) 1.82126
add(uint32_t) 1.76
add(int64_t) 1.76
add(uint64_t) 1.83223
sub(float) 1.96617
sub(double) 1.98491
sub(long double) 3.55474
sub(u4_4) 1.77006
sub(s3_4) 1.72983
sub(u8_8) 1.72983
sub(s7_8) 1.72983
sub(u16_16) 1.73966
sub(s15_16) 1.85051
sub(u32_32) 1.88229
sub(s31_32) 1.87063
sub(int8_t) 1.76
sub(uint8_t) 1.74994
sub(int16_t) 1.82126
sub(uint16_t) 1.83794
sub(int32_t) 1.89074
sub(uint32_t) 1.85417
sub(int64_t) 1.83703
sub(uint64_t) 2.04914
mul(float) 1.9376
mul(double) 1.93097
mul(long double) 102.446
mul(u4_4) 2.46583
mul(s3_4) 2.09189
mul(u8_8) 2.08
mul(s7_8) 2.18697
mul(u16_16) 2.12571
mul(s15_16) 2.10789
mul(u32_32) 2.10789
mul(s31_32) 2.10789
mul(int8_t) 1.76
mul(uint8_t) 1.78011
mul(int16_t) 1.8432
mul(uint16_t) 1.76914
mul(int32_t) 1.78011
mul(uint32_t) 2.19086
mul(int64_t) 1.7696
mul(uint64_t) 1.79017
div(float) 5.12
div(double) 7.64343
div(long double) 8.304
div(u4_4) 3.82171
div(s3_4) 3.82171
div(u8_8) 3.84
div(s7_8) 3.8
div(u16_16) 9.152
div(s15_16) 11.232
div(u32_32) 30.8434
div(s31_32) 34
div(int8_t) 3.82171
div(uint8_t) 3.82171
div(int16_t) 3.8
div(uint16_t) 3.82171
div(int32_t) 3.82171
div(uint32_t) 3.81806
div(int64_t) 10.2286
div(uint64_t) 8.304
Among the slowest types are long double
. It is likely that they are
emulated in software. The next slowest operations are fixed-point
multiply and divide operations - especially with 64-bit types. This is
because values need to be promoted temporarily to double-width types.
This is a known fixed-point technique which inevitably experiences
slowdown where a 128-bit type is required on a 64-bit system.
Here is a section of the disassembly of the s15:16 multiply call:
The two 32-bit numbers are multiplied together and the result shifted
down - much as it would if raw int
values were used. The efficiency
of this operation varies with the exponent. An exponent of zero should
mean no shift at all.
A fast sqrt
implementation has not yet been tested with
fixed_point
. (The naive implementation takes over 300ns.) For this
reason, a magnitude-squared function is measured, combining multiply
and add operations:
Only real number formats are tested:
float 2.42606
double 2.08
long double 4.5056
s3_4 2.768
s7_8 2.77577
s15_16 2.752
s31_32 4.10331
Again, the size of the type seems to have the largest impact.
A similar operation includes a comparison and branch:
float 3.46011
double 3.48
long double 6.4
s3_4 3.88
s7_8 4.5312
s15_16 3.82171
s31_32 5.92
Again, fixed-point and native performance are comparable.