Conceptadvanced
Fixed-point arithmetic
Also called fixed-point, fixed point, fixed-point number, binary scaling, scaled integer, Q format, Q notation, Q15, Q16.16, _Fract, _Accum.
A fixed-point number is an integer with an implied scale, such as cents for money or 1/65536 in a Q16.16 value. Addition is integer addition, and a product needs a rescale and a wider type.
- Applies to
- core-languages
Idea
A fixed-point number is an integer with a scale that the program knows but does not store. Wikipedia: "the value 1.23 can be stored in a variable as the integer value 123 with an implicit scaling factor of 1/100"1. "Dollar amounts, for example, are often stored with exactly two fractional digits, representing the cents (1/100 of a dollar)."1 The scale is a negative power of the base, and "The most common variants are decimal (base 10) and binary (base 2)."1
The hardware sees only integers. "Internally, however, there is no separation, and the distinction between the two groups of digits is defined only by the programs that handle such numbers."1 So the program must keep track of the scale of each value.
SHIFT = 16
ONE = 1 << SHIFT
def to_fix(x):
return round(x * ONE)
def to_float(f):
return f / ONE
def mul(a, b):
return (a * b + (ONE >> 1)) >> SHIFT
def fits_int32(v):
return -(2**31) <= v < 2**31
a, b = to_fix(1.5), to_fix(2.25)
print("1.5 as Q16.16:", a)
print("1.5 * 2.25:", to_float(mul(a, b)))
t = to_fix(0.1)
print("0.1 as Q16.16:", t, "=", to_float(t))
print("10 * 0.1:", to_float(t * 10))
big = to_fix(300.0)
print("300 * 300 fits in Q16.16:", "yes" if fits_int32(mul(big, big)) else "no")
print("raw 300 * 300 fits in 64 bits:", "yes" if -(2**63) <= big * big < 2**63 else "no")
1.5 as Q16.16: 98304
1.5 * 2.25: 3.375
0.1 as Q16.16: 6554 = 0.100006103515625
10 * 0.1: 1.00006103515625
300 * 300 fits in Q16.16: no
raw 300 * 300 fits in 64 bits: yes
The block uses a binary scale of 1/65536, which is 16 fraction bits. 1.5 and 2.25 have exact binary fractions, so their product is exact. 0.1 is not exact in binary, and the error grows when the value is used 10 times. 90000 does not fit in the 32-bit Q16.16 format, but the raw product fits in 64 bits.
How it works
Addition and subtraction. Two values with the same scale add as integers. These operations "yield the exact mathematical result, as long as no overflow occurs"1, and "If overflow happens, it occurs like with ordinary integers of the same signedness."1 Two values with different scales must first be converted to one scale.
Multiplication. The product of the two integers has the product of the two scales. "The result will be exact, with no rounding, provided that it does not overflow the receiving variable."1 Wikipedia's example: 0.123, stored as 123 with scale 1/1000, times 2.5, stored as 25 with scale 1/10, gives 3075 with scale 1/10000, which is 0.30751. The product needs more bits: "the product is up to twice the width of the two factors, so to accurately represent the result, the receiving variable requires twice the width as the operands"1. To bring the product back to the scale of the operands, the program divides it by the scale. "In binary, it is common to use a scaling factor that is a power of two. After the multiplication, the scaling factor can be divided away by shifting right."1
Rounding after the rescale. A right shift or an integer division gives "a flooring division"1. To round half up, the program adds "a 'rounding addend' of half of the scaling factor before shifting"1. The mul function in the first block does this with ONE >> 1.
Division. A quotient of two fixed-point values has the quotient of the two scales, and much of the precision can be lost. Wikipedia's example: 34.56 with scale 1/100, divided by 1.234 with scale 1/1000, gives the integer 3 with scale 10, which is 301. So a program scales the dividend up before it divides.
Q notation. Binary fixed-point formats are often named in Q notation. "Q7.8 means that the signed fixed point numbers in this format have 7 bits for the integer part and 8 bits for the fraction part"2, with one more bit for the sign, so Q7.8 is a 16-bit word2. "There is an ARM variation of the Q notation that explicitly adds the sign bit to the integer part."2 In it, the same format is Q8.82. The Q multiplication code in Wikipedia multiplies two 16-bit values into a 32-bit value, adds a rounding constant, shifts, and saturates the result to the 16-bit range2.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | TypeScript has no fixed-point type, so a program keeps a number or a bigint with a scale, as in JavaScript. No example file exists. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Idiom | Kotlin has no fixed-point type, so a program keeps a Long with a scale or uses java.math.BigDecimal at a set scale. No example file exists because kotlinc is not installed. |
| SQL | Native | SQL has NUMERIC and DECIMAL, which are fixed-point decimal types with a declared precision and scale. No example file exists. |
| Bash | Idiom | Bash arithmetic expansion has integers only, so a script keeps an amount in cents and prints the two parts with a division and a remainder. No example file exists. |
| PowerShell | Idiom | PowerShell has no fixed-point type; a script uses the .NET decimal type or an integer with a scale. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no arithmetic. |
| CSS | Does not apply | CSS has no fixed-point number type that a style sheet can use for arithmetic. |
| Regular expressions | Does not apply | A pattern matches digits as text but does no arithmetic. |
| Language | Verdict | Fixed-point support |
|---|---|---|
| Python | idiom | an int with a scale; decimal for decimal values |
| JavaScript | idiom | a number or bigint with a scale |
| TypeScript | idiom | as JavaScript |
| Java | idiom | a long with a scale; BigDecimal has a scale |
| Kotlin | idiom | as Java |
| C# | idiom | a long with a scale; decimal |
| Go | idiom | an int64 with a scale |
| Rust | idiom | an i64 with a scale; crates |
| C | idiom | an integer with a scale; GCC _Fract and _Accum on some targets |
| C++ | idiom | an integer with a scale, often in a class |
| Bash | idiom | an integer with a scale in $(( )) |
| PowerShell | idiom | [decimal] or an integer with a scale |
| SQL | native | NUMERIC and DECIMAL with a precision and a scale |
| Regex | n/a | no arithmetic |
| HTML | n/a | no arithmetic |
| CSS | n/a | no fixed-point type |
Older languages had fixed-point types: Wikipedia names "COBOL, Ada, JOVIAL, and Coral 66"1, and says that "More modern languages usually do not offer any fixed-point data types or support for scaling factor conversion."1 In their place, "they can be implemented by the programmer, with explicit scaling conversion, in any programming language that supports explicit integer types"1. That is the idiom in each language above. On the other hand, "all relational databases and the SQL notation support fixed-point decimal arithmetic and storage of numbers"1.
C has a proposal for fixed-point types. "As an extension, GNU C supports fixed-point types as defined in the N1169 draft of ISO/IEC DTR 18037."3 The types are _Fract and _Accum, with _Sat forms that saturate3, but "Not all targets support fixed-point types."3
Java's BigDecimal is a decimal type with a scale that can change: it "consists of an arbitrary precision integer unscaled value and a 32-bit integer scale"4. Its setScale method changes the scale, and it multiplies or divides the unscaled value "by the appropriate power of ten to maintain its overall value"4. A program that keeps every BigDecimal at scale 2 uses it as a decimal fixed-point type for money.
from decimal import ROUND_HALF_UP, Decimal
def show(cents):
sign = "-" if cents < 0 else ""
cents = abs(cents)
return f"{sign}{cents // 100}.{cents % 100:02d}"
price = 1999
total = price * 3
print("3 x 19.99:", show(total))
rate = 825
tax = (total * rate + 5000) // 10000
print("tax at 8.25 percent:", show(tax))
print("0.1 + 0.2 as floats:", 0.1 + 0.2)
print("10 + 20 cents:", show(10 + 20))
d = Decimal("59.97") * Decimal("0.0825")
print("Decimal product:", d)
print("quantized:", d.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
print("-7 cents // 2:", -7 // 2)
3 x 19.99: 59.97
tax at 8.25 percent: 4.95
0.1 + 0.2 as floats: 0.30000000000000004
10 + 20 cents: 0.30
Decimal product: 4.947525
quantized: 4.95
-7 cents // 2: -4
- Verdict: idiom. Python has no fixed-point type, so the block keeps money as an
intnumber of cents and the tax rate as anintwith a scale of 1/10000. - Adding 5000 before the division by 10000 rounds half up for positive values.
//is floored, so a negative amount rounds toward minus infinity. decimal.Decimalwithquantizegives the same result with a decimal type.
#include <cstdint>
#include <iostream>
template <int F>
class Fixed {
public:
static Fixed from_ratio(std::int32_t num, std::int32_t den) {
return Fixed(static_cast<std::int32_t>((std::int64_t{num} << F) / den));
}
Fixed operator+(Fixed o) const { return Fixed(raw_ + o.raw_); }
Fixed operator*(Fixed o) const {
std::int64_t p = std::int64_t{raw_} * o.raw_ + (std::int64_t{1} << (F - 1));
return Fixed(static_cast<std::int32_t>(p >> F));
}
double to_double() const { return static_cast<double>(raw_) / (std::int64_t{1} << F); }
std::int32_t raw() const { return raw_; }
private:
explicit Fixed(std::int32_t raw) : raw_(raw) {}
std::int32_t raw_;
};
int main() {
using Q16 = Fixed<16>;
Q16 a = Q16::from_ratio(3, 2);
Q16 b = Q16::from_ratio(9, 4);
std::cout << "1.5 * 2.25: " << (a * b).to_double() << '\n';
std::cout << "1.5 + 2.25: " << (a + b).to_double() << '\n';
Q16 tenth = Q16::from_ratio(1, 10);
std::cout << "1/10 raw: " << tenth.raw() << '\n';
Q16 big = Q16::from_ratio(300, 1);
std::cout << "300 * 300: " << (big * big).to_double() << '\n';
}
1.5 * 2.25: 3.375
1.5 + 2.25: 3.75
1/10 raw: 6553
300 * 300: 24464
- Verdict: idiom. C++ has no fixed-point type in the standard library, so a program writes a class like
Fixed<F>, whereFis the number of fraction bits. from_ratiodivides with truncation, so 1/10 is 6553, not 6554. The product is computed in 64 bits, but the cast back to 32 bits wraps 90000 to 24464 with no error.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
static final int SHIFT = 16;
static int mul(int a, int b) {
long p = ((long) a * b + (1L << (SHIFT - 1))) >> SHIFT;
return Math.toIntExact(p);
}
public static void main(String[] args) {
int a = 3 << (SHIFT - 1);
int b = 9 << (SHIFT - 2);
System.out.println("1.5 * 2.25: " + mul(a, b) / 65536.0);
int big = 300 << SHIFT;
try {
System.out.println(mul(big, big));
} catch (ArithmeticException e) {
System.out.println("300 * 300: ArithmeticException");
}
long cents = 1999L * 3;
System.out.printf("3 x 19.99: %d.%02d%n", cents / 100, cents % 100);
BigDecimal tax = new BigDecimal("59.97").multiply(new BigDecimal("0.0825"));
System.out.println("tax: " + tax + ", scale " + tax.scale());
System.out.println("tax at scale 2: " + tax.setScale(2, RoundingMode.HALF_UP));
}
}
1.5 * 2.25: 3.375
300 * 300: ArithmeticException
3 x 19.99: 59.97
tax: 4.947525, scale 6
tax at scale 2: 4.95
- Verdict: idiom. Java has no fixed-point type. The block multiplies two Q16.16
intvalues in along, thenMath.toIntExactthrows when the result does not fit back in anint. BigDecimalhas an explicit scale. The product of a scale 2 value and a scale 4 value has scale 6, andsetScalerounds it back to scale 2.
#include <stdint.h>
#include <stdio.h>
#define Q 15
#define K (1 << (Q - 1))
static int16_t sat16(int32_t x) {
if (x > 0x7FFF) {
return 0x7FFF;
}
if (x < -0x8000) {
return -0x8000;
}
return (int16_t)x;
}
static int16_t q_mul(int16_t a, int16_t b) {
int32_t temp = (int32_t)a * (int32_t)b;
temp += K;
return sat16(temp >> Q);
}
static double q_to_double(int16_t x) {
return x / 32768.0;
}
int main(void) {
int16_t half = 16384;
int16_t minus_one = -32768;
int16_t p = q_mul(half, half);
printf("0.5 * 0.5: %d = %g\n", p, q_to_double(p));
p = q_mul(minus_one, minus_one);
printf("-1 * -1: %d = %.15g\n", p, q_to_double(p));
p = q_mul(minus_one, half);
printf("-1 * 0.5: %d = %g\n", p, q_to_double(p));
return 0;
}
0.5 * 0.5: 8192 = 0.25
-1 * -1: 32767 = 0.999969482421875
-1 * 0.5: -16384 = -0.5
- Verdict: idiom. Standard C has no fixed-point type. The block is the Q15 multiplication from Wikipedia's Q notation page: a 32-bit product, a rounding constant, a shift and a saturation to 16 bits.
- -1 × -1 is 1, which Q15 cannot hold, so the result saturates to 32767, the value nearest to 1.
- GCC has
_Fractand_Accumtypes as an extension, but only on some targets.
using System;
const int Shift = 16;
static int Mul(int a, int b) => checked((int)(((long)a * b + (1L << (Shift - 1))) >> Shift));
int a = 3 << (Shift - 1);
int b = 9 << (Shift - 2);
Console.WriteLine($"1.5 * 2.25: {Mul(a, b) / 65536.0}");
int big = 300 << Shift;
try
{
Console.WriteLine(Mul(big, big));
}
catch (OverflowException)
{
Console.WriteLine("300 * 300: OverflowException");
}
long cents = 1999L * 3;
Console.WriteLine($"3 x 19.99: {cents / 100}.{cents % 100:D2}");
decimal tax = 59.97m * 0.0825m;
Console.WriteLine($"decimal tax: {tax}");
Console.WriteLine($"rounded: {Math.Round(tax, 2, MidpointRounding.AwayFromZero)}");
Console.WriteLine($"Math.Round(2.345m, 2): {Math.Round(2.345m, 2)}");
1.5 * 2.25: 3.375
300 * 300: OverflowException
3 x 19.99: 59.97
decimal tax: 4.947525
rounded: 4.95
Math.Round(2.345m, 2): 2.34
- Verdict: idiom. C# has no fixed-point type. The block keeps Q16.16 values in an
int, multiplies in along, andcheckedthrows when the result does not fit. - The
decimaltype keeps the scale of each value, so money is exact.Math.Roundon adecimalrounds half to even by default, so 2.345 becomes 2.34.
const SHIFT = 16n;
const ONE = 1n << SHIFT;
const toFix = (x) => BigInt(Math.round(x * Number(ONE)));
const mul = (a, b) => (a * b + (ONE >> 1n)) >> SHIFT;
const toNumber = (f) => Number(f) / Number(ONE);
console.log(`1.5 * 2.25: ${toNumber(mul(toFix(1.5), toFix(2.25)))}`);
const q = new Int32Array(1);
q[0] = Number(mul(toFix(300), toFix(300)));
console.log(`300 * 300 in an Int32Array: ${q[0] / 65536}`);
const show = (cents) => `${Math.trunc(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
console.log(`3 x 19.99: ${show(1999 * 3)}`);
console.log(`0.1 + 0.2 as numbers: ${0.1 + 0.2}`);
console.log(`10 + 20 cents: ${show(10 + 20)}`);
1.5 * 2.25: 3.375
300 * 300 in an Int32Array: 24464
3 x 19.99: 59.97
0.1 + 0.2 as numbers: 0.30000000000000004
10 + 20 cents: 0.30
- Verdict: idiom. JavaScript has no fixed-point type. The block keeps a Q16.16 value in a
bigintand money as a whole number of cents. - The store into an
Int32Arraykeeps the low 32 bits, so 90000 wraps to 90000 - 65536 = 24464 with no error.
package main
import "fmt"
const shift = 16
func mul(a, b int32) int64 {
return (int64(a)*int64(b) + 1<<(shift-1)) >> shift
}
func main() {
a := int32(3 << (shift - 1))
b := int32(9 << (shift - 2))
fmt.Println("1.5 * 2.25:", float64(mul(a, b))/65536)
big := int32(300 << shift)
p := mul(big, big)
fmt.Println("300 * 300 in int64:", float64(p)/65536)
fmt.Println("300 * 300 in int32:", float64(int32(p))/65536)
cents := int64(1999 * 3)
fmt.Printf("3 x 19.99: %d.%02d\n", cents/100, cents%100)
fmt.Println("-7 >> 1:", int32(-7)>>1, "and -7 / 2:", int32(-7)/2)
}
1.5 * 2.25: 3.375
300 * 300 in int64: 90000
300 * 300 in int32: 24464
3 x 19.99: 59.97
-7 >> 1: -4 and -7 / 2: -3
- Verdict: idiom. Go has no fixed-point type. The block multiplies two Q16.16
int32values in anint64. - The conversion of the product to
int32keeps the low 32 bits, so 90000 wraps to 24464 with no error. - A right shift rounds toward minus infinity, and
/truncates toward zero, so the two rescale methods differ for negative values.
const SHIFT: u32 = 16;
fn mul(a: i32, b: i32) -> Result<i32, std::num::TryFromIntError> {
let p = (a as i64 * b as i64 + (1i64 << (SHIFT - 1))) >> SHIFT;
i32::try_from(p)
}
fn mul_sat(a: i32, b: i32) -> i32 {
let p = (a as i64 * b as i64 + (1i64 << (SHIFT - 1))) >> SHIFT;
p.clamp(i32::MIN as i64, i32::MAX as i64) as i32
}
fn main() {
let a: i32 = 3 << (SHIFT - 1);
let b: i32 = 9 << (SHIFT - 2);
println!("1.5 * 2.25: {}", mul(a, b).unwrap() as f64 / 65536.0);
let big: i32 = 300 << SHIFT;
println!("300 * 300 is an error: {}", if mul(big, big).is_err() { "yes" } else { "no" });
println!("300 * 300 saturated: {}", mul_sat(big, big) as f64 / 65536.0);
let cents: i64 = 1999 * 3;
println!("3 x 19.99: {}.{:02}", cents / 100, cents % 100);
}
1.5 * 2.25: 3.375
300 * 300 is an error: yes
300 * 300 saturated: 32767.99998474121
3 x 19.99: 59.97
- Verdict: idiom. The standard library has no fixed-point type, so the block keeps Q16.16 values in an
i32and multiplies in ani64. i32::try_fromreturns an error when the product does not fit, andclampsaturates it to the largest Q16.16 value.
Variations and related ideas
- Decimal and binary scale. A decimal scale, such as 1/100, holds amounts of money exactly. A binary scale, such as 1/65536, lets the program rescale with a shift.
- Saturation. A fixed-point operation can clamp the result to the largest or smallest value in place of a wrap. The Q multiplication code in Wikipedia does this2, and the GCC
_Sattypes do it too3. See Integer overflow behaviour. - Integer multiples of a unit. The term also covers "representing fractional values as integer multiples of some fixed small unit, e.g., a fractional amount of hours as an integer multiple of ten-minute intervals"1.
- Floating point. A floating-point number stores its scale as an exponent in each value. See Floating-point arithmetic.
Pitfalls
- Overflow in the product. The product of two values needs about twice the bits of each value. A Q16.16 multiplication in 32 bits overflows for most values. Multiply in a 64-bit type, then shift.
- Mixed scales. An addition of a value in cents to a value in dollars gives a wrong result with no error, because the hardware sees only integers. Keep the scale in the type name or in a wrapper type.
- Truncation in the rescale. A right shift rounds toward minus infinity, and C integer division rounds toward zero (see Integer division and modulo). Both give a small bias that grows in a long loop. Add the rounding addend first.
- A decimal value in a binary scale. 0.1 has no exact binary fraction, so a binary fixed-point format rounds it, as the first block shows. Money needs a decimal scale.
- A float in the middle. A conversion of a fixed-point value to a float and back can change the last digit. Keep the arithmetic in integers.
Cost
Fixed-point arithmetic is integer arithmetic, plus a shift or a division to rescale a product. "Fixed-point number representation is often contrasted to the more complicated and computationally demanding floating-point representation."1 Since most processors now have a fast floating-point unit, Wikipedia says that fixed point is used "only in special situations, such as in low-cost embedded microprocessors and microcontrollers; in applications that demand high speed or low power consumption or small chip area, like image, video, and digital signal processing; or when their use is more natural for the problem"1. It "is still the norm for field-programmable gate array (FPGA) implementations"1.
History
"Fixed-point representation was the norm in mechanical calculators."1 COBOL, Ada, JOVIAL and Coral 66 had fixed-point types, and "Most of those languages were designed between 1955 and 1990."1 In 2008, ISO published a draft technical report that adds the _Fract and _Accum types to C "for the benefit of programs running on embedded DSP processors"1. "The popular TrueType font format uses 32-bit signed binary fixed-point with 26 bits to the left of the decimal for some numeric values in its instructions."1
References
- Fixed-point arithmetic, Wikipedia, the introduction; Representation; Operations; Hardware support; Computer language implementations; Software application examples
- Q (number format), Wikipedia, the introduction; Multiplication
- Fixed-Point Types, Using the GNU Compiler Collection (GCC), the whole page
- BigDecimal, Java SE 27 API, the class description; setScale
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag KZCXPG Edit this page History Report an error Markdown