APyFixedΒΆ

APyTypes provide a class for configurable floating-point numbers: APyFixed.

The numbers are represented as the underlying integer, the total number of bits and integer bits. However, there are also convenience methods to do this either from a float, a string, or a bit-pattern. One can also supply the number of fractional bits; two out of the three (total, integer, and fractional bits) must be supplied.

from apytypes import APyFixed

a = APyFixed(7, 4, 2)
a
APyFixed(7, bits=6, int_bits=4)
b = APyFixed.from_float(-2.25, int_bits=3, frac_bits=2)
b
APyFixed(23, bits=5, int_bits=3)
c = APyFixed.from_str("3.75", bits=6, frac_bits=3)
c
APyFixed(30, bits=6, int_bits=3)

Standard arithmetic operations are supported. The resulting number of bits depends on the operation. For addition and subtraction, the maximum number of integer bits and fractional bits are used. A single integer bit is added to make sure that the computation does not overflow.

a + b
APyFixed(126, bits=7, int_bits=5)

For multiplication, the number of integer bits and fractional bits is the sum of the number of integer bits and fractional bits of the included operands, respectively.

a * c
APyFixed(210, bits=12, int_bits=7)

Standard string formatting is supported

str(a)
'1.75'

Comparisons with integers and floats are supported

(b >= -2.25, a == 1.75)
(True, True)

Arithmetic with Python integers and floats is supported, although not recommended, by automatically casting the number to the same format of the APyType-object

b + 3.5
APyFixed(5, bits=6, int_bits=4)

Which is equivalent to

b + APyFixed.from_float(3.5, int_bits=b.int_bits, frac_bits=b.frac_bits)
APyFixed(5, bits=6, int_bits=4)

However, while it is convenient to let APyTypes convert numbers automatically, it is not recommended as it can yield unexpected results. Consider the expression

1.25 + 1.25 + APyFixed.from_float(2, int_bits=4, frac_bits=1)
APyFixed(9, bits=6, int_bits=5)

which would yield a different result from

APyFixed.from_float(2, int_bits=4, frac_bits=1) + 1.25 + 1.25
APyFixed(10, bits=7, int_bits=6)

To change the word length of a APyFixed, the method cast() can be used

(a + b).cast(4, 3)
APyFixed(124, bits=7, int_bits=4)

Total running time of the script: (0 minutes 0.002 seconds)

Gallery generated by Sphinx-Gallery