# The FixedPoint Class¶

Examples are just a click away

Boxes like this link to example code.

class fixedpoint.FixedPoint(init, /, signed=None, m=None, n=None, *, overflow='clamp', rounding='auto', overflow_alert='error', implicit_cast_alert='warning', mismatch_alert='warning', str_base=16)
Parameters
• init (float or int or str or FixedPoint) – Initial value. This argument is required and positional, meaning it cannot be keyworded and must come first in the list of arguments.

• signed (bool) – Signedness, part of the Q format specification. When left unspecified, sign() is used to deduce signedness. This argument can be keyworded.

• m (int) – Number of integer bits, part of the Q format specification. When left unspecified, min_m() is used to deduce initial integer bit width, after which trim() is used after rounding to minimize integer bits. This argument can be keyworded.

• n (int) – Number of fractional bits, part of the Q format specification. When left unspecified, min_n() is used to deduce fractional bit width. This argument can be keyworded.

• overflow (str) –

Specifies what shall happen when the value overflows its integer bit width. Valid options are:

• 'clamp' (default when left unspecified)

• 'wrap'

• rounding (str) –

Specifies how superfluous fractional bits are rounded away. Valid options are:

• 'convergent' (default for signed when left unspecified)

• 'nearest' (default for unsigned when left unspecified)

• 'in'

• 'out'

• 'up'

• 'down'

Specifies the notification scheme when overflow occurs. Valid options are:

• 'error' (default when left unspecified)

• 'warning'

• 'ignore'

Specifies the notification scheme when 2 FixedPoints with non-matching properties undergo arithmetic. Valid options are:

• 'error'

• 'warning' (default when left unspecified)

• 'ignore'

Specifies the notification scheme when implicit casting is performed and the resultant FixedPoint is not valued the same as the original number. Valid options are:

• 'error'

• 'warning' (default when left unspecified)

• 'ignore'

• str_base (int) –

Casting a FixedPoint to a str generates a bit string in the base specified by str_base. Valid options are:

• 16 (default when left unspecified)

• 10

• 8

• 2

Raises
• if init is a str and any of signed, m, or n are not specified.

• if more than m + n bits are present in init (when init is a str).

• if an invalid Q format is specified.

• TypeError – if init is not an int, float, str, or FixedPoint and cannot be cast to a float.

• FixedPointOverflowError – if overflow_alert is 'error' and m is too small to represent init.

from_int(val)
Parameters

val (int) – Value to set the FixedPoint to.

Set the value of the FixedPoint from an integer value. Affects only integer bits (since integer require no fractional bits). Must fit into the Q format already designated by the object, otherwise overflow will occur.

from_float(val)
Parameters

val (float) – Value to set the FixedPoint to.

Set the value of the FixedPoint. Must fit into the Q format already designated by the object, otherwise rounding and/or overflow will occur.

from_string(val)
from_str(val)
Parameters

val (str) – Value to set the FixedPoint bits to.

Directly set the bits of the FixedPoint, using the Q format already designated by the object. May be a decimal, binary, octal, or hexadecimal string, the latter three of which require a '0b', '0o', or '0x' radix, respectively.

FixedPoint Properties

signed
Type

bool

Getter

True for signed, False for unsigned.

Setter

Set signedness.

Raises

Change signedness of number. Note that if the MSb is 0, the value of the number will not change. Overflow occurs if the MSb is 1.

m
Type

int

Getter

Number of integer bits in the FixedPoint number.

Setter

Set the number of integer bits in the FixedPoint number.

Raises

When the number of integer bits increases, sign extension occurs for signed numbers, and 0-padding occurs for unsigned numbers. When then number of integer bits decreases, overflow handling may occur (per the overflow property) if the FixedPoint value is too large for the new integer bit width.

n
Type

int

Getter

Number of fractional bits in the FixedPoint number.

Setter

Set the number of fractional bits in the FixedPoint number.

Raises

When the number of fractional bits increases, 0s are appended to the fixed point number. When the number of fractional bits decreases, rounding may occur (per the rounding property), which in turn may cause overflow (per the overflow property) if the integer portion of the rounded result is too large to fit within the current integer bit width.

str_base
Type

int

Getter

Base of the string generated by str.

Setter

Set the base of the string generated by str.

Using the builtin python str function on a FixedPoint casts the object to a string. The string is the bits of the FixedPoint number in the base specified by str_base, but without the radix. Must be one of:

• 16

• 10

• 8

• 2

overflow
Type

str

Getter

The current overflow scheme.

Setter

Set the overflow scheme.

Overflow occurs when the number of bits required to represent a value exceeds the number of integer bits available (m). The overflow property of a FixedPoint specifies how to handle overflow. Must be one of:

• 'clamp'

• 'wrap'

rounding
Type

str

Getter

The current rounding scheme.

Setter

Set the rounding scheme.

Rounding occurs when fractional bits must be removed from the object. Some rounding schemes can cause overflow in certain circumstances. Must be one of:

• 'convergent'

• 'nearest'

• 'in'

• 'out'

• 'up'

• 'down'

overflow_alert
Type

str

Getter

The current overflow_alert scheme.

Setter

Set the overflow_alert scheme.

When overflow occurs, the overflow_alert property indicates how you are notified. Must be one of:

• 'error'

• 'warning'

• 'ignore'

mismatch_alert
Type

str

Getter

The current mismatch_alert scheme.

Setter

Set the mismatch_alert scheme.

When 2 FixedPoints interact to create another FixedPoint, the properties assigned to the new object must be resolved from the 2 original objects. Whenever properties between these 2 objects do not match, the mismatch_alert property indicates how you are notified. Must be one of:

• 'warning'

• 'error'

• 'ignore'

implicit_cast_alert
Type

str

Getter

The current implicit_cast_alert scheme.

Setter

Set the implicit_cast_alert scheme.

Some operations allow a FixedPoint to interact with another object that is not a FixedPoint. Typically, the other object will need to be cast to a FixedPoint, and is done so internally in the class method. If error exists after the cast to FixedPoint, the implicit_cast_alert property indicates how you are notified. Must be one of:

• 'warning'

• 'error'

• 'ignore'

bits
Type

FixedPointBits

Getter

Bits of the fixed point number.

This is the read-only bits of the FixedPoint, stored as an integer.

Indexing, slicing, and mapping is available with the FixedPointBits class.

bitmask
Type

int

Getter

Bitmask of the FixedPoint number.

Integer bitmask, equivalent to $$2^{m + n} - 1$$.

clamped
Type

bool

Getter

True if the value of the FixedPoint number is equal to it minimum or maximum value. False otherwise.

qformat
Type

str

Getter

Q format of the FixedPoint number.

The string takes the form UQm.n, where:

• U is only present for unsigned numbers

• m is the number of integer bits

• n is the number of fractional bits

Arithmetic Operators

__add__(augend)
__iadd__(augned)
__radd__(addend)

Note

These are the + and += operators.

Parameters
Returns

Return type

FixedPoint

Raises

Note

$$\it{sum} = \it{addend} + \it{augend}$$

Addition using the + and += operators are full precision; bit growth will occur:

If both augend or addend are unsigned, the result is unsigned, otherwise the result will be signed.

__sub__(subtrahend)
__isub__(subtrahend)
__rsub__(minuend)

Note

These are the - and -= operators.

Parameters
Returns

Difference of minuend and subtrahend

Return type

FixedPoint

Raises

Note

$$\it{difference} = \it{minuend} - \it{subtrahend}$$

Subtraction using the - and -= operators are full precision; bit growth will occur.

If both minuend or subtrahend are unsigned, the result is unsigned, otherwise the result will be signed.

Overflow can occur for unsigned subtraction.

__mul__(multiplier)
__imul__(multiplier)
__rmul__(multiplicand)

Note

These are the * and *= operators.

Parameters
Returns

Product of multiplicand and multiplier

Return type

FixedPoint

Raises

Note

$$\it{product} = \it{multiplicand} \times \it{multiplier}$$

Multiplication using the * and *= operators are full precision; bit growth will occur.

If both multiplicand or multiplier are unsigned, the result is unsigned, otherwise the result will be signed.

__pow__(exponent)
__ipow__(exponent)

Note

These are the ** and **= operators.

Parameters

exponent (int) – The exponent to the FixedPoint base. Must be positive.

Returns

Result of the base raised to the exponent power.

Return type

FixedPoint

Note

$$\it{result} = \it{base}^{\it{exponent}}$$

Exponentiation using the ** and **= operators are full precision; bit growth will occur.

The result has the same signedness as the base.

Only positive integers are supported as the exponent.

Comparison Operators

__lt__(other)
__le__(other)
__gt__(other)
__ge__(other)
__eq__(other)
__ne__(other)

Note

These are the <, <=, >, >=, == and != operators.

Parameters

other (FixedPoint or int or float) – Numeric object to compare to

Returns

True if the comparison is true, False otherwise

Return type

bool

__cmp__(other)
Parameters

other (FixedPoint or int or float) – Numeric object to compare to

Returns

• a negative number if the object is < other

• 0 if the object == other

• a positive number if the object is > other

Return type

int

Generic comparison object. Not used for comparisons in python 3 but used internally by all other comparisons.

Bitwise Operators

__lshift__(nbits)
__ilshift__(nbits)

Note

These are the << and <<= operators.

Parameters

nbits (int) – Number of bits to shift left.

Return type

FixedPoint

Bit shifting does not change the FixedPoint’s Q format. The nbits leftmost bits are discarded.

To keep bits after shifting, multiply the object by $$2^{nbits}$$ instead of using the << or <<= operator.

If nbits < 0, bits are shifted right using >> or >>= by abs(nbits) instead.

__rshift__(nbits)
__irshift__(nbits)

Note

These are the >> and >>= operators.

Parameters

nbits (int) – Number of bits to shift right.

Returns

Original FixedPoint with bits shifted right.

Return type

FixedPoint

Bit shifting does not change the FixedPoint’s Q format. The nbits rightmost bits are discarded.

To keep bits after shifting, multiply the object by $$2^{-nbits}$$ instead of using the >> or >>= operator.

For signed numbers, sign extension occurs.

If nbits < 0, bits are shifted right using << or <<= by abs(nbits) instead.

__and__(other)
__iand__(other)
__rand__(other)

Note

These are the & and &= operators.

Parameters

other (int or FixedPoint) – Object to bitwise AND with

Returns

Original object’s bits bitwise ANDed with other’s bits.

Return type

FixedPoint

When ANDing 2 FixedPoints, the binary point is not aligned.

After ANDing, the result is masked with the leftmost FixedPoint.bitmask and assigned to the bits of the return value.

__or__(other)
__ior__(other)
__ror__(other)

Note

These are the | and |= operators.

Parameters

other (int or FixedPoint) – Object to bitwise OR with

Returns

Original object’s bits bitwise ORed with other’s bits.

Return type

FixedPoint

When ORing 2 FixedPoints, the binary point is not aligned.

After ORing, the result is masked with the leftmost FixedPoint.bitmask and assigned to the bits of the return value.

__xor__(other)
__ixor__(other)
__rxor__(other)

Note

These are the ^ and ^= operators.

Parameters

other (int or FixedPoint) – Object to bitwise XOR with

Returns

Original object’s bits bitwise XORed with other’s bits.

Return type

FixedPoint

When XORing 2 FixedPoints, the binary point is not aligned.

After XORing, the result is masked with the leftmost FixedPoint.bitmask and assigned to the bits of the return value.

Unary Operators

__invert__()

Note

This is the unary ~ operator.

Returns

Copy of original object with bits inverted.

Return type

FixedPoint

__pos__()

Note

This is the unary + operator.

Returns

Copy of original object.

Return type

FixedPoint

__neg__()

Note

This is the unary - operator.

Returns

Negated copy of original object negated.

Return type

FixedPoint

Raises

In an attempt to minimize user error, unsigned numbers cannot be negated. The idea is that you should be doing this very intentionally.

Built-in Function Support

__abs__()

Note

This is the built-in abs() function.

Returns

Absolute value.

Return type

FixedPoint

Raises

FixedPointOverflowError – if the absolute value of a negative-valued number is larger than the Q format allows (raised only if overflow_alert is 'error').

Signedness does not change.

__int__()

Note

This is the built-in int function.

Returns

Only the integer bits of the FixedPoint number.

Return type

int

Fractional bits are ignored, which is the same as rounding down.

__float__()

Note

This is the built-in float function.

Returns

Floating point cast of the FixedPoint number.

Return type

float

When casting to a float would result in an OverflowError, float('inf') or float('-inf') is returned instead.

Warning

A typical Python float follows IEEE 754 double-precision format, which means there’s 52 mantissa bits and a sign bit (you can verify this by examining sys.float_info). Thus for FixedPoint word lengths beyond 52 bits, the float cast may lose precision or resolution.

__bool__()

Note

This is the built-in bool function.

Returns

False if FixedPoint.bits are non-zero, True otherwise.

Return type

bool

__index__()

Note

This is the built-in hex(), oct(), and bin() functions.

Returns

Bits of the FixedPoint number.

Return type

int

Calling hex(), oct(), or bin() on a FixedPoint generates a str with the FixedPoint.bits represented as a hexadecimal, octal, or binary string. The radix prepends the bits, which do not contain any left-padded zeros.

__str__()

Note

This is the built-in str function.

Returns

Bits of the FixedPoint number, left padded to the number of bits in the number, in the base specified by the str_base property.

Return type

str

Calling str() will generate a hexadecimal, octal, or binary string (according to the str_base property setting) without the radix, and 0-padded to the actual bit width of the FixedPoint number. Decimal strings are not 0-padded.

This string represents the bits of the number, thus will always be non-negative.

Signedness does not change.

__format__()

Note

This is the built-in str.format() and format() function, and also applies to f-strings.

Returns

Formatted string, various formats available.

Return type

str

A FixedPoint can be formatted as a str, float, or int would, depending on the format string syntax.

Table 1 Standard Format Specifier Parsing Summary
format_spec
type

Formatted Type

Formatted Value
(given x = FixedPoint(...))

's'

str

str(x)
(depends on x.str_base)

'q'

x.qformat

'b'
(binary)

int

x.bits

'd'
(decimal)
'o'
(octal)
'x'
(lowercase
'X'
(uppercase

'...m' 1

x.bits['int']
(integer bits only)

'...n' 1

x.bits['frac']
(fractional bits only)

'e'

float

float(x)

'E'

'f'

'F'

'g'

'G'

'%'

1 Append to the specifier of another formatted int. E.g., 'bn' would format the fractional bits of x in binary.

__len__()

Note

This is the built-in len() function..

Returns

Number of bits in the FixedPoint.

Return type

int

__repr__()

Note

This is the built-in repr() function, which is also the output shown when a FixedPoint is not assigned to a variable.

Returns

Python executable code; a str representation of the object.

Return type

str

This generates a code string that will exactly reproduce the FixedPoint’s value and properties.

Bit Resizing Methods

resize(m, n, /, rounding=None, overflow=None, alert=None)
Parameters
Raises

FixedPointOverflowError – if resizing causes overflow (raised only if alert - or overflow_alert if alert is not specified - is 'error').

Fractional bits are resized first, them integer bits. Bit sizes can grow or shrink from their current value.

Rounding, overflow handling, and overflow alert notification severity can be temporarily modified within the scope of this method. I.e., specifying the rounding, overflow, or alert arguments will only take effect within this method; it will not permanently change the property settings of the object. If left unspecified, the current property setting is used.

trim(ints=None, fracs=None)
Parameters
• ints (bool) – Set to True to trim off superfluous integer bits

• fracs (bool) – Set to True to trim off superfluous fractional bits

Trims off excess bits, including:

• up to n trailing 0s

• for unsigned numbers:

• for signed numbers:

• up to m - 1 leading 0s for positive numbers, leaving one leading 0 in front of the first 1 encountered

• up to m - 1 leading 1s, for negative numbers, leaving one leading 1 in front of the first 0 encountered

Resultant Q format is always valid. For the FixedPoint value of 0, resulting Q format is [U]Q1.0.

Opt to trim off only fractional bits or only integer bits by setting fracs or ints, respectively, to True. When left unspecified, both integer and fractional bits are trimmed.

Rounding Methods

__round__(n)

Note

This is the built-in round() function.

Parameters

n (int) – Number of bits remaining after round

Returns

A copy of the FixedPoint rounded to n bits.

Return type

FixedPoint

Raises

FixedPointOverflowError – if rounding causes overflow (raised only if the overflow_alert property setting is 'error').

Rounds a copy of the FixedPoint using the rounding scheme specified by the rounding property setting.

Refer to FixedPoint.resize() for more details.

__floor__()

Note

This is the built-in math.floor() function. It does not modify the object given to it, but creates a copy and operates on it instead.

Return type

FixedPoint

Rounds to the integer closest to $$-\infty$$, but does not modify the fractional bit width.

__ceil__()

Note

This is the built-in math.ceil() function. It does not modify the object given to it, but creates a copy and operates on it instead.

Return type

FixedPoint

RaisesFixedPointOverflowError

if the integer value of the FixedPoint is already at its maximum possible value (raised only if overflow_alert is 'error')

Rounds to the integer closest to $$+\infty$$, leaving 0 fractional bits. For values other than 0, this requires m to be non-zero.

__trunc__()

Note

This is the built-in math.trunc() function. It does not modify the object given to it, but creates a copy and operates on it instead.

Return type

FixedPoint

Rounds to the integer closest to $$-\infty$$, leaving 0 fractional bits. If m is 0, it is changed to 1, otherwise m is not modified.

round(n)
Parameters

n (int) – Number of fractional bits remaining after rounding

Raises

FixedPointOverflowError – if rounding causes overflow (raised only if overflow_alert is 'error')

Rounds the FixedPoint using the rounding scheme specified by the rounding property setting.

convergent(n)
round_convergent(n)
Parameters

n (int) – Number of fractional bits remaining after rounding

Raises

FixedPointOverflowError – if rounding causes overflow (raised only if overflow_alert is 'error')

Rounds to n fractional bits, biased toward the nearest value with ties rounding to the nearest even value.

round_nearest(n)
Parameters

n (int) – Number of fractional bits remaining after rounding

Raises

FixedPointOverflowError – if rounding causes overflow (raised only if overflow_alert is 'error')

Rounds the FixedPoint to n fractional bits, biased toward the nearest value with ties rounding to $$+\infty$$.

round_in(n)
Parameters

n (int) – Number of fractional bits remaining after rounding

Rounds the FixedPoint to n fractional bits toward 0.

round_out(n)
Parameters

n (int) – Number of fractional bits remaining after rounding

Raises

FixedPointOverflowError – if rounding causes overflow (raised only if overflow_alert is 'error')

Rounds the FixedPoint to n fractional bits, biased toward the nearest value with ties rounding away from 0.

round_down(n)
Parameters

n (int) – Number of fractional bits remaining after rounding

Rounds the FixedPoint to n fractional bits toward $$-\infty$$.

round_up(n)
Parameters

n (int) – Number of fractional bits remaining after rounding

Raises

FixedPointOverflowError – if rounding causes overflow (raised only if overflow_alert is 'error')

Rounds the FixedPoint to n fractional bits toward $$+\infty$$.

keep_msbs(m, n, /, rounding=None, overflow=None, alert=None)
Parameters
Raises

FixedPointOverflowError – if rounding causes overflow (raised only if alert - or overflow_alert if alert is not specified - is 'error')

Rounds away LSb(s), leaving m + n bit(s), using the rounding scheme specified, then interprets the result with m integer bits and n fractional bits.

The rounding, overflow handling, and overflow alert notification schemes can be temporarily modified within the scope of this method. I.e., specifying the rounding, overflow, or alert arguments will only take effect within this method; it will not permanently change the property settings of the object. The current property setting for any of these unspecified arguments is used.

While other rounding functions cannot round beyond the fractional bits in a FixedPoint, keep_msbs() will keep an arbitrary number of the FixedPoint’s most significant bits, regardless of its current Q format. The resulting Q format must be valid.

Overflow Handling

clamp(m, /, alert=None)
Parameters
Raises

FixedPointOverflowError – if new integer bit width is too small to represent the FixedPoint object value (raised only if alert - or overflow_alert if alert is not specified - is 'error')

Reduces the number of integer bits in the FixedPoint to m, clamping to the minimum or maximum value on overflow.

The overflow alert notification scheme can be temporarily modified within the scope of the method by using the alert argument. When left unspecified, the overflow_alert property setting is used.

wrap(m, /, alert=None)
Parameters
Raises

FixedPointOverflowError – if new integer bit width is too small to represent the FixedPoint object value (raised only if alert - or overflow_alert if alert is not specified - is 'error')

Reduces the number of integer bits in the FixedPoint to m, masking away the removed integer bits.

The overflow alert notification scheme can be temporarily modified within the scope of the method by using the alert argument. When left unspecified, the overflow_alert property setting is used.

keep_lsbs(m, n, /, overflow=None, alert=None)
Parameters
Raises

FixedPointOverflowError – if new m + n bits is too small to represent the FixedPoint value (raised only if alert - or overflow_alert if alert is not specified - is 'error')

Removes MSb(s), leaving m + n bit(s), using the overflow scheme specified, then interprets the result with m integer bits and n fractional bits.

The overflow handling and overflow alert notification schemes can be temporarily modified within the scope of this method. I.e., specifying the overflow or alert arguments will only take effect within this method; it will not permanently change the property settings of the object. The current property setting for any of these unspecified arguments is used.

While other overflow handling functions cannot remove MSbs beyond their integer bits in a FixedPoint, keep_lsbs() will keep an arbitrary number of the FixedPoint’s least significant bits, regardless of its current Q format. The resulting Q format must be valid.

Context Management

__enter__()
__exit__(exc_type, *args)
__call__(*, safe_retain=False, **props)

Note

This is the built-in with statement in conjunction with the () operator.

Parameters
• safe_retain (bool) – Set to True to retain the changes made within the context as long as no exceptions were raised. Set to False (or leave unspecified) if the the changes made within the context are to be undone when the context exits.

• props

Any keyword-able argument from the FixedPoint constructor, including:

• signed (bool)

• m (int)

• n (int)

• overflow (str)

• rounding (str)

• str_base (int)

Raises

While the __call__ method is not typically associated with the context manager, the FixedPoint class uses this method to assign attributes temporarily (or permanently, with appropriate use of the safe_retain keyword) to the FixedPoint called, within the context of the with statement.

Using the __call__ method is optional when safe_retain does not need to be True.

static enable_logging()

Enables logging to fixedpoint.log, located in the root directory of the fixedpoint module.

On initial import, logging is disabled.

Any time this method is called, fixedpoint.log is erased.

static disable_logging()

Disables logging to fixedpoint.log.

classmethod sign(val)
Parameters

val (FixedPoint or int or float) – Value from which to discern the sign.

Returns

• -1 if val < 0

• +1 if val > 0

• 0 if val == 0

Return type

int

Determine the sign of a number.

classmethod min_m(val, /, signed=None)
Parameters
• val (int or float) – Value to analyze

• signed (bool) – True if signed, False if unsigned

Returns

Minimum value for FixedPoint.m for which val can be represented without overflow.

Return type

int

Calculate the minimum value for FixedPoint.m for which va can be represented without overflow. If signed is not specified, it is deduced from the value of val. When val < 0, signed is ignored.

Worst case rounding is assumed (e.g., min_m(3.25) returns 3, in case 3.25 needs to be rounded up to 4).

classmethod min_n(val)
Parameters

val (float) – Value to analyze

Returns

Minimum value for FixedPoint.n for which val can be represented exactly.

Return type

int