Skip to content

fxp

pyfxp.fxp

fxp(x, spec)

Convert a numeric value to fixed-point representation using a pre-defined fixed-point specification.

This function behaves like fxpt, but instead of requiring multiple arguments (qi, qf, signed, rnd, ovf), it accepts a single FxpSpec named tuple (or tuple) that encapsulates all format parameters. This makes it easier to reuse and pass fixed-point type definitions in a compact, Numba-friendly form.

Parameters:

Name Type Description Default
x (int, float or array - like)

The input value(s) to convert.

required
spec FxpSpec or tuple

A fixed-point specification tuple or named tuple with the following fields:

  • qi : int Number of integer bits (including sign bit if signed=True).
  • qf : int Number of fractional bits.
  • signed : bool Whether the fixed-point format is signed.
  • rnd : int Rounding method to apply. Supported methods (same as in fxpt):
    • TRUNC (0): Bit truncation; rounds toward negative infinity.
    • CEIL (1): Round toward positive infinity.
    • TO_ZERO (2): Round toward zero.
    • AWAY (3): Round away from zero.
    • HALF_UP (4): Round to nearest; ties toward positive infinity.
    • HALF_DOWN (5): Round to nearest; ties toward negative infinity.
    • HALF_EVEN (6): Round to nearest; ties to even.
    • HALF_ZERO (7): Round to nearest; ties toward zero.
    • HALF_AWAY (8): Round to nearest; ties away from zero.
  • ovf : int Overflow handling method. Supported methods (same as in fxpt):
    • WRAP (0): Wrap around.
    • SAT (1): Saturate to max/min representable value.
    • ERROR (2): Raise an error on overflow.
required

Returns:

Type Description
float or ndarray

Fixed-point representation of the input value(s).

Notes
  • Equivalent to: >>> fxp(x, Q(qi, qf, signed, rnd, ovf)) == fxpt(x, qi, qf, signed, rnd, ovf)
  • Uses ARM-style Q-format notation (Qm.n), where:
    • m = qi → number of integer bits (including signed bit if signed=True)
    • n = qf → number of fractional bits
  • Designed to be fully compatible with Numba @njit mode

Examples:

>>> from pyfxp import Q, fxp
>>> from pyfxp.constants import TRUNC, WRAP
>>> import numpy as np
>>> np.pi
>>> 3.14159265358979
>>> Q3_4T = Q(3, 4, signed=True, rnd=TRUNC, ovf=WRAP)      # Q3.4 format (3 integer bits, 4 fractional bits)
>>> fxp(np.pi, Q3_4T)
3.125