Note
Go to the end to download the full example code.
APyFloatΒΆ
APyTypes provide a class for configurable floating-point numbers: APyFloat
.
The numbers are created from the sign-bit, the exponent and the mantissa (without hidden one) and the corresponding wordlengths. However, there are also convenience methods to do this either from a float or from a bit-pattern.
APyFloat(sign=1, exp=3, man=5, exp_bits=4, man_bits=5)
b = APyFloat.from_float(2.25, 3, 2)
b
APyFloat(sign=0, exp=4, man=0, exp_bits=3, man_bits=2)
c = APyFloat.from_bits(int("10110101"), 3, 4)
c
APyFloat(sign=1, exp=1, man=5, exp_bits=3, man_bits=4)
Standard arithmetic operations are supported. The resulting number of exponent and mantissa bits are the maximum of the involved terms.
APyFloat(sign=0, exp=7, man=30, exp_bits=4, man_bits=5)
APyFloat(sign=0, exp=1, man=17, exp_bits=4, man_bits=5)
Standard string formatting is supported
str(a)
'-0.0722656'
Comparisons with integers and floats are supported
(False, False)
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 + 1.125
APyFloat(sign=0, exp=4, man=2, exp_bits=3, man_bits=2)
Which is equivalent to
b + APyFloat.from_float(1.125, exp_bits=b.exp_bits, man_bits=b.man_bits, bias=b.bias)
APyFloat(sign=0, exp=4, man=2, exp_bits=3, man_bits=2)
However, while it is convenient to let APyTypes convert numbers automatically, it is not recommended as it can yield unexpected results. Consider the expression
2 + 2 + APyFloat.from_float(8, exp_bits=4, man_bits=1)
APyFloat(sign=0, exp=10, man=1, exp_bits=4, man_bits=1)
which would yield a different result from
APyFloat.from_float(8, exp_bits=4, man_bits=1) + 2 + 2
APyFloat(sign=0, exp=10, man=0, exp_bits=4, man_bits=1)
To change the word length of a APyFloat, the method cast()
can be used
APyFloat(sign=0, exp=8, man=0, exp_bits=4, man_bits=3)
Total running time of the script: (0 minutes 0.007 seconds)