From b51dd402f53bb60b3d62b231081dd7c1a4c96619 Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Tue, 7 Jul 2026 13:11:41 +0200 Subject: [PATCH 01/18] Implement next_up and next_after for more types --- CHANGELOG.md | 1 + lib/apytypes/_apytypes.pyi | 6 ++++ lib/test/apyfixed/test_methods.py | 35 +++++++++++++++++++++++ lib/test/apyfixedarray/test_methods.py | 39 ++++++++++++++++++++++++++ lib/test/apyfloatarray/test_methods.py | 11 ++++++++ src/apyfixed.cc | 22 +++++++++++++++ src/apyfixed.h | 6 ++++ src/apyfixed_wrapper.cc | 2 ++ src/apyfixedarray.cc | 32 +++++++++++++++++++++ src/apyfixedarray.h | 6 ++++ src/apyfixedarray_wrapper.cc | 2 ++ src/apyfloatarray.cc | 22 +++++++++++++++ src/apyfloatarray.h | 7 +++++ src/apyfloatarray_wrapper.cc | 2 ++ 14 files changed, 193 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f85aac83..b5885e9bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - SIMD for single-limb fixed-point complex array multiplication and division. - Many creation functions have a `spec` argument where one can provide an `APy*` object that the new object will inherit all properties (number of bits etc) from. +- `next_up` and `next_down` for real fixed-point scalars and real arrays. ### Fixed diff --git a/lib/apytypes/_apytypes.pyi b/lib/apytypes/_apytypes.pyi index 06bd51684..fc052e9f5 100644 --- a/lib/apytypes/_apytypes.pyi +++ b/lib/apytypes/_apytypes.pyi @@ -4810,6 +4810,8 @@ class APyFixed: """ def __abs__(self) -> APyFixed: ... + def next_up(self) -> APyFixed: ... + def next_down(self) -> APyFixed: ... def __float__(self) -> float: ... def __repr__(self) -> str: ... def __str__(self, base: int = 10) -> str: ... @@ -6341,6 +6343,8 @@ class APyFixedArray: def __matmul__(self, rhs: APyCFixedArray) -> APyCFixedArray | APyCFixed: ... def __repr__(self) -> str: ... def __abs__(self) -> APyFixedArray: ... + def next_up(self) -> APyFixedArray: ... + def next_down(self) -> APyFixedArray: ... def __str__(self, base: int = 10) -> str: ... def __getitem__( self, @@ -7451,6 +7455,8 @@ class APyFloatArray: @overload def __ge__(self, arg: APyFloat, /) -> NDArray[numpy.bool]: ... def __abs__(self) -> APyFloatArray: ... + def next_up(self) -> APyFloatArray: ... + def next_down(self) -> APyFloatArray: ... @overload def __radd__(self, arg: int, /) -> APyFloatArray: ... @overload diff --git a/lib/test/apyfixed/test_methods.py b/lib/test/apyfixed/test_methods.py index a6f8a03f4..f69525eae 100644 --- a/lib/test/apyfixed/test_methods.py +++ b/lib/test/apyfixed/test_methods.py @@ -15,6 +15,41 @@ def test_to_bits(): ) +def test_next_up_down(): + fx = APyFixed.from_float(1.0, int_bits=4, frac_bits=2) + assert fx.next_up().is_identical(APyFixed.from_float(1.25, int_bits=4, frac_bits=2)) + assert fx.next_down().is_identical( + APyFixed.from_float(0.75, int_bits=4, frac_bits=2) + ) + + +def test_next_up_down_saturates_at_bounds(): + # Maximum positive value (0111): next_up must not overflow to the minimum + # negative value. + max_val = APyFixed(0b0111, int_bits=4, frac_bits=0) + assert max_val.next_up().is_identical(max_val) + # One step below max should still increment normally. + assert APyFixed(0b0110, int_bits=4, frac_bits=0).next_up().is_identical(max_val) + + # Minimum negative value (1000): next_down must not underflow to the maximum + # positive value. + min_val = APyFixed(0b1000, int_bits=4, frac_bits=0) + assert min_val.next_down().is_identical(min_val) + # One step above min should still decrement normally. + assert APyFixed(0b1001, int_bits=4, frac_bits=0).next_down().is_identical(min_val) + + +def test_next_up_down_saturates_multi_limb(): + # Use a bit-width large enough to require multiple limbs on both 32- and + # 64-bit builds. + bits = 200 + max_val = APyFixed((1 << (bits - 1)) - 1, int_bits=bits, frac_bits=0) + assert max_val.next_up().is_identical(max_val) + + min_val = APyFixed(-(1 << (bits - 1)), int_bits=bits, frac_bits=0) + assert min_val.next_down().is_identical(min_val) + + def test_getitem_bit_indexing(): fx = APyFixed(0xA4, int_bits=4, frac_bits=4) diff --git a/lib/test/apyfixedarray/test_methods.py b/lib/test/apyfixedarray/test_methods.py index dbd5488c6..bb35b8f46 100644 --- a/lib/test/apyfixedarray/test_methods.py +++ b/lib/test/apyfixedarray/test_methods.py @@ -21,6 +21,45 @@ def test_ndim(fixed_array: type[APyCFixedArray]): assert fixed_array([range(3), range(3)], bits=1, int_bits=0).ndim == 2 +def test_next_up_down_fixed_array(): + a = APyFixedArray.from_float([1.0, -2.0, 3.5], int_bits=6, frac_bits=2) + + up = a.next_up() + down = a.next_down() + + for i in range(len(a)): + assert up[i].is_identical(a[i].next_up()) + assert down[i].is_identical(a[i].next_down()) + + +def test_next_up_down_fixed_array_saturates_at_bounds(): + int_bits, frac_bits = 4, 0 + max_val = APyFixed(0b0111, int_bits=int_bits, frac_bits=frac_bits) + min_val = APyFixed(0b1000, int_bits=int_bits, frac_bits=frac_bits) + + a = APyFixedArray( + [0b0111, 0b0110, 0b1000, 0b1001], int_bits=int_bits, frac_bits=frac_bits + ) + up = a.next_up() + down = a.next_down() + + # Max positive stays fixed on next_up; other elements step normally. + assert up[0].is_identical(max_val) + assert up[1].is_identical(max_val) + assert up[2].is_identical(min_val.next_up()) + assert up[3].is_identical( + APyFixed(0b1001, int_bits=int_bits, frac_bits=frac_bits).next_up() + ) + + # Max negative stays fixed on next_down; other elements step normally. + assert down[0].is_identical(max_val.next_down()) + assert down[1].is_identical( + APyFixed(0b0110, int_bits=int_bits, frac_bits=frac_bits).next_down() + ) + assert down[2].is_identical(min_val) + assert down[3].is_identical(min_val) + + @pytest.mark.parametrize("fixed_array", [APyFixedArray, APyCFixedArray]) def test_squeeze(fixed_array: type[APyCFixedArray]): a = fixed_array([[1], [2], [3]], bits=2, int_bits=2) diff --git a/lib/test/apyfloatarray/test_methods.py b/lib/test/apyfloatarray/test_methods.py index a1069c648..26f1c8ed9 100644 --- a/lib/test/apyfloatarray/test_methods.py +++ b/lib/test/apyfloatarray/test_methods.py @@ -87,6 +87,17 @@ def test_python_deepcopy( assert not a.is_identical(c) +def test_next_up_down_float_array(): + a = APyFloatArray.from_float([1.0, 2.0, -3.0], exp_bits=8, man_bits=7) + + up = a.next_up() + down = a.next_down() + + for i in range(len(a)): + assert up[i].is_identical(a[i].next_up()) + assert down[i].is_identical(a[i].next_down()) + + @pytest.mark.float_array @pytest.mark.parametrize("float_array", [APyFloatArray, APyCFloatArray]) def test_array_from_float_raises(float_array: type[APyCFloatArray]): diff --git a/src/apyfixed.cc b/src/apyfixed.cc index a433368ef..9fe649114 100644 --- a/src/apyfixed.cc +++ b/src/apyfixed.cc @@ -560,6 +560,28 @@ apy_limb_t APyFixed::increment_lsb() noexcept ); } +APyFixed APyFixed::next_up() const +{ + if (*this == get_max(_bits, _int_bits)) { + // Already at the maximum positive value, do not overflow + return *this; + } + APyFixed result = *this; + result.increment_lsb(); + return result; +} + +APyFixed APyFixed::next_down() const +{ + if (*this == get_min(_bits, _int_bits)) { + // Already at the maximum negative value, do not underflow + return *this; + } + APyFixed result = *this; + apy_inplace_subtraction_single_limb(result._data.begin(), result._data.end(), 1); + return result; +} + // Function to create a Python fractions.Fraction object nb::object APyFixed::to_fraction() const { diff --git a/src/apyfixed.h b/src/apyfixed.h index db9620151..54c8deaac 100644 --- a/src/apyfixed.h +++ b/src/apyfixed.h @@ -261,6 +261,12 @@ class APyFixed { //! Increment the LSB without making the fixed-point number wider. Return carry out apy_limb_t increment_lsb() noexcept; + //! Get the next representable fixed-point number in the same format. + APyFixed next_up() const; + + //! Get the previous representable fixed-point number in the same format. + APyFixed next_down() const; + //! Convert the underlying bit pattern to a Python long integer nb::int_ to_bits() const; diff --git a/src/apyfixed_wrapper.cc b/src/apyfixed_wrapper.cc index 5df7ed421..ffc75e859 100644 --- a/src/apyfixed_wrapper.cc +++ b/src/apyfixed_wrapper.cc @@ -556,6 +556,8 @@ void bind_fixed(nb::module_& m) * Dunder methods */ .def("__abs__", &APyFixed::abs) + .def("next_up", &APyFixed::next_up) + .def("next_down", &APyFixed::next_down) .def("__float__", &APyFixed::operator double) .def("__repr__", &APyFixed::repr) .def("__str__", &APyFixed::to_string, nb::arg("base") = 10) diff --git a/src/apyfixedarray.cc b/src/apyfixedarray.cc index f4bf48205..076c35fb8 100644 --- a/src/apyfixedarray.cc +++ b/src/apyfixedarray.cc @@ -1904,6 +1904,38 @@ APyFixedArray APyFixedArray::abs() const return result; } +APyFixedArray APyFixedArray::next_up() const +{ + APyFixedArray result = *this; + const APyFixed max_val = APyFixed::get_max(_bits, _int_bits); + auto it_begin = result._data.begin(); + for (std::size_t i = 0; i < result._nitems; i++) { + auto it_end = it_begin + result._itemsize; + // Do not overflow past the maximum positive value + if (!std::equal(it_begin, it_end, max_val.read_data().begin())) { + limb_vector_add_one_lsb_inplace(it_begin, it_end); + } + it_begin = it_end; + } + return result; +} + +APyFixedArray APyFixedArray::next_down() const +{ + APyFixedArray result = *this; + const APyFixed min_val = APyFixed::get_min(_bits, _int_bits); + auto it_begin = result._data.begin(); + for (std::size_t i = 0; i < result._nitems; i++) { + auto it_end = it_begin + result._itemsize; + // Do not underflow past the maximum negative value + if (!std::equal(it_begin, it_end, min_val.read_data().begin())) { + apy_inplace_subtraction_single_limb(it_begin, it_end, 1); + } + it_begin = it_end; + } + return result; +} + APyFixedArray APyFixedArray::operator-() const { // Increase word length of result by one diff --git a/src/apyfixedarray.h b/src/apyfixedarray.h index 94926dfbe..e136e1aad 100644 --- a/src/apyfixedarray.h +++ b/src/apyfixedarray.h @@ -293,6 +293,12 @@ class APyFixedArray : public APyArray { //! Elementwise absolute value APyFixedArray abs() const; + //! Elementwise next representable value in the same format. + APyFixedArray next_up() const; + + //! Elementwise previous representable value in the same format. + APyFixedArray next_down() const; + /*! * Create a new array with the same shape as `*this`, but with all elements * set to zero. diff --git a/src/apyfixedarray_wrapper.cc b/src/apyfixedarray_wrapper.cc index a3939f175..c5416c4c3 100644 --- a/src/apyfixedarray_wrapper.cc +++ b/src/apyfixedarray_wrapper.cc @@ -1854,6 +1854,8 @@ void bind_fixed_array(nb::module_& m) ) .def("__repr__", &APyFixedArray::repr) .def("__abs__", &APyFixedArray::abs) + .def("next_up", &APyFixedArray::next_up) + .def("next_down", &APyFixedArray::next_down) .def("__str__", &APyFixedArray::to_string, nb::arg("base") = 10) // Iteration and friends diff --git a/src/apyfloatarray.cc b/src/apyfloatarray.cc index 1b2968605..68a200c2a 100644 --- a/src/apyfloatarray.cc +++ b/src/apyfloatarray.cc @@ -222,6 +222,28 @@ APyFloatArray APyFloatArray::abs() const return res; } +APyFloatArray APyFloatArray::next_up() const +{ + APyFloatArray result(_shape, exp_bits, man_bits, bias); + APyFloat element(exp_bits, man_bits, bias); + for (std::size_t i = 0; i < _nitems; i++) { + element.set_data(_data[i]); + result._data[i] = element.next_up().get_data(); + } + return result; +} + +APyFloatArray APyFloatArray::next_down() const +{ + APyFloatArray result(_shape, exp_bits, man_bits, bias); + APyFloat element(exp_bits, man_bits, bias); + for (std::size_t i = 0; i < _nitems; i++) { + element.set_data(_data[i]); + result._data[i] = element.next_down().get_data(); + } + return result; +} + APyFloatArray APyFloatArray::operator*(const APyFloatArray& rhs) const { if (_shape != rhs._shape) { diff --git a/src/apyfloatarray.h b/src/apyfloatarray.h index 156723d02..c8311d7f5 100644 --- a/src/apyfloatarray.h +++ b/src/apyfloatarray.h @@ -142,6 +142,13 @@ class APyFloatArray : public APyArray { //! Absolute value APyFloatArray abs() const; + + //! Elementwise next representable value in the same format. + APyFloatArray next_up() const; + + //! Elementwise previous representable value in the same format. + APyFloatArray next_down() const; + //! Elementwise R-division with floating-point scalar APyFloatArray rdiv(const APyFloat& lhs) const; diff --git a/src/apyfloatarray_wrapper.cc b/src/apyfloatarray_wrapper.cc index 43cffab08..ba2bad6a7 100644 --- a/src/apyfloatarray_wrapper.cc +++ b/src/apyfloatarray_wrapper.cc @@ -162,6 +162,8 @@ void bind_float_array(nb::module_& m) .def(nb::self <= nb::self, CMP("__le__", "APyFloatArray")) .def(nb::self >= nb::self, CMP("__ge__", "APyFloatArray")) .def("__abs__", &APyFloatArray::abs) + .def("next_up", &APyFloatArray::next_up) + .def("next_down", &APyFloatArray::next_down) /* * Arithmetic operators with integers From b06d11c695968930d19c3b5fd12d03fef75c5945 Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Wed, 5 Aug 2026 11:52:22 +0200 Subject: [PATCH 02/18] Add apy.nextafter --- CHANGELOG.md | 1 + docs/api/arrayfunctions.rst | 2 + lib/apytypes/__init__.py | 2 + lib/apytypes/_array_functions.py | 61 +++++++++++++++++ lib/test/test_array_functions.py | 111 +++++++++++++++++++++++++++++++ src/apyarray.h | 47 +++++++++++++ src/apyfixedarray_wrapper.cc | 3 + src/apyfloatarray_wrapper.cc | 3 + 8 files changed, 230 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b5885e9bb..e7acfbdd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Many creation functions have a `spec` argument where one can provide an `APy*` object that the new object will inherit all properties (number of bits etc) from. - `next_up` and `next_down` for real fixed-point scalars and real arrays. +- Utility function `nextafter` for real arrays. ### Fixed diff --git a/docs/api/arrayfunctions.rst b/docs/api/arrayfunctions.rst index 5866ed212..b62789b36 100644 --- a/docs/api/arrayfunctions.rst +++ b/docs/api/arrayfunctions.rst @@ -59,3 +59,5 @@ Array utility functions .. autofunction:: apytypes.outer .. autofunction:: apytypes.shape + +.. autofunction:: apytypes.nextafter diff --git a/lib/apytypes/__init__.py b/lib/apytypes/__init__.py index 76962ccab..50f388937 100644 --- a/lib/apytypes/__init__.py +++ b/lib/apytypes/__init__.py @@ -45,6 +45,7 @@ import_csv, meshgrid, moveaxis, + nextafter, ones, ones_like, outer, @@ -101,6 +102,7 @@ "meshgrid", "moveaxis", "n_threads", + "nextafter", "ones", "ones_like", "outer", diff --git a/lib/apytypes/_array_functions.py b/lib/apytypes/_array_functions.py index 504bae32c..27c742b0c 100644 --- a/lib/apytypes/_array_functions.py +++ b/lib/apytypes/_array_functions.py @@ -2847,6 +2847,67 @@ def outer(a: APyArray, b: APyArray) -> APyArray: return outer(b) +@overload +def nextafter( + x1: APyFloatArray, x2: APyFloatArray | APyFloat | float | int +) -> APyFloatArray: ... +@overload +def nextafter( + x1: APyFixedArray, x2: APyFixedArray | APyFixed | float | int +) -> APyFixedArray: ... + + +def nextafter( + x1: APyFloatArray | APyFixedArray, + x2: APyFloatArray | APyFixedArray | APyFloat | APyFixed | float | int, +) -> APyFloatArray | APyFixedArray: + """ + Return the next representable value of `x1` in the direction of `x2`, element-wise. + `x1` and `x2` do not need to be of the same type. + If `x1.shape` != `x2.shape`, they must be broadcastable to a common shape + (which becomes the shape of the output). + + .. versionadded:: 0.6 + + Parameters + ---------- + x1 : :class:`APyFloatArray` or :class:`APyFixedArray` + Values to get the next representable value of. + x2 : :class:`APyFloatArray`, :class:`APyFixedArray`, :class:`APyFixed`, :class:`APyFloat`, :class:`int`, or :class:`float` + Direction in which to get the next representable value. + + Returns + ------- + :class:`APyArray` + Same type as `x1`. + """ + if not isinstance(x1, APyFloatArray | APyFixedArray): + raise TypeError(f"nextafter: x1 must be a real APyArray, got {type(x1)}") + + try: + nextafter_impl = x1._nextafter + except AttributeError: + raise TypeError(f"Type {type(x1)} has no attribute `_nextafter`") + + if type(x2) is not type(x1): + if isinstance(x2, int | float | APyFixed | APyFloat): + if isinstance(x1, APyFixedArray): + x2 = type(x1).from_float( + [x2], int_bits=x1.int_bits, frac_bits=x1.frac_bits + ) + else: + x2 = type(x1).from_float( + [x2], exp_bits=x1.exp_bits, man_bits=x1.man_bits, bias=x1.bias + ) + else: + raise TypeError( + "nextafter: x2 must be an array of the same type as x1, or one of " + f"`int`, `float`, `APyFixed`, `APyFloat`, got {type(x2)}" + ) + + return nextafter_impl(x1, x2) + + # ============================================================================= # Helpers # ============================================================================= diff --git a/lib/test/test_array_functions.py b/lib/test/test_array_functions.py index 2babdf288..6628a974a 100644 --- a/lib/test/test_array_functions.py +++ b/lib/test/test_array_functions.py @@ -22,6 +22,7 @@ identity, meshgrid, moveaxis, + nextafter, ones, ones_like, ravel, @@ -551,6 +552,116 @@ def test_meshgrid(array_type): assert ww.is_identical(ww_ref) +def test_nextafter_float_array_elementwise(): + x1 = APyFloatArray.from_float([1.0, 2.0, 3.0], exp_bits=5, man_bits=10) + x2 = APyFloatArray.from_float([2.0, 1.0, 3.0], exp_bits=5, man_bits=10) + + y = nextafter(x1, x2) + + assert y[0].is_identical(x1[0].next_up()) + assert y[1].is_identical(x1[1].next_down()) + assert y[2].is_identical(x2[2]) + + +@pytest.mark.parametrize("start_sign", [0, 1]) +@pytest.mark.parametrize("direction_sign", [0, 1]) +def test_nextafter_float_array_signed_zero(start_sign, direction_sign): + x1 = APyFloatArray([start_sign], [0], [0], exp_bits=5, man_bits=10) + x2 = APyFloatArray([direction_sign], [0], [0], exp_bits=5, man_bits=10) + + assert nextafter(x1, x2).is_identical(x2) + + +def test_nextafter_float_array_broadcasting(): + x1 = APyFloatArray.from_float([[1.0], [2.0]], exp_bits=5, man_bits=10) + x2 = APyFloatArray.from_float([[0.0, 1.0, 3.0]], exp_bits=5, man_bits=10) + + y = nextafter(x1, x2) + + assert y.shape == (2, 3) + assert y[0, 0].is_identical(x1[0, 0].next_down()) + assert y[0, 1].is_identical(x2[0, 1]) + assert y[0, 2].is_identical(x1[0, 0].next_up()) + assert y[1, 0].is_identical(x1[1, 0].next_down()) + assert y[1, 1].is_identical(x1[1, 0].next_down()) + assert y[1, 2].is_identical(x1[1, 0].next_up()) + + +def test_nextafter_fixed_array_elementwise(): + x1 = APyFixedArray.from_float([1.0, 2.0, 3.0], int_bits=6, frac_bits=4) + x2 = APyFixedArray.from_float([2.0, 1.0, 3.0], int_bits=6, frac_bits=4) + + y = nextafter(x1, x2) + + assert y[0].is_identical(x1[0].next_up()) + assert y[1].is_identical(x1[1].next_down()) + assert y[2].is_identical(x2[2]) + + +def test_nextafter_complex_float_array_raises(): + x1 = APyCFloatArray.from_complex([1.0 + 1.0j, 2.0 - 1.0j], exp_bits=5, man_bits=10) + x2 = APyCFloatArray.from_complex([2.0 - 1.0j, 1.0 + 1.0j], exp_bits=5, man_bits=10) + + assert not hasattr(x1, "_nextafter") + with pytest.raises(TypeError, match="nextafter: x1 must be a real APyArray"): + _ = nextafter(x1, x2) + + +def test_nextafter_complex_fixed_array_raises(): + x1 = APyCFixedArray.from_complex([1.0 + 1.0j, 2.0 - 1.0j], int_bits=6, frac_bits=4) + x2 = APyCFixedArray.from_complex([2.0 - 1.0j, 1.0 + 1.0j], int_bits=6, frac_bits=4) + + assert not hasattr(x1, "_nextafter") + with pytest.raises(TypeError, match="nextafter: x1 must be a real APyArray"): + _ = nextafter(x1, x2) + + +@pytest.mark.parametrize("array_type", [APyFloatArray, APyFixedArray]) +@pytest.mark.parametrize( + "direction", + [ + 2.0 + 0.0j, + APyCFloat.from_complex(2.0 + 1.0j, exp_bits=5, man_bits=10), + APyCFixed.from_complex(2.0 + 1.0j, int_bits=6, frac_bits=4), + APyCFloatArray.from_complex([2.0 + 1.0j], exp_bits=5, man_bits=10), + APyCFixedArray.from_complex([2.0 + 1.0j], int_bits=6, frac_bits=4), + ], +) +def test_nextafter_complex_direction_raises(array_type, direction): + x1 = array_type.from_float([1.0], 5, 10) + + with pytest.raises( + TypeError, match="nextafter: x2 must be an array of the same type as x1" + ): + _ = nextafter(x1, direction) + + +@pytest.mark.parametrize("array_type", [APyFloatArray, APyFixedArray]) +@pytest.mark.parametrize( + "direction", + [ + 2, + 2.0, + APyFloat.from_float(2.0, exp_bits=5, man_bits=10), + APyFixed.from_float(2.0, int_bits=6, frac_bits=4), + ], +) +def test_nextafter_real_direction(array_type, direction): + x1 = array_type.from_float([1.0], 5, 10) + + assert nextafter(x1, direction).is_identical(x1.next_up()) + + +def test_nextafter_type_raises(): + fp = APyFloatArray.from_float([1.0], exp_bits=5, man_bits=10) + fx = APyFixedArray.from_float([1.0], int_bits=5, frac_bits=5) + + with pytest.raises( + TypeError, match="nextafter: x2 must be an array of the same type as x1" + ): + _ = nextafter(fp, fx) + + @pytest.mark.parametrize("shape", [(i, j) for i in range(1, 5) for j in range(1, 5)]) def test_zeros(shape: tuple[int, int]): def check_zeros( diff --git a/src/apyarray.h b/src/apyarray.h index 9ddb4cff5..4a7cfde94 100644 --- a/src/apyarray.h +++ b/src/apyarray.h @@ -30,6 +30,7 @@ namespace nb = nanobind; #include // std::set #include // std::string #include // std::string_view +#include // std::is_same_v #include // std::in_place_type #include // std::variant @@ -1275,6 +1276,52 @@ template class APyArray : public APyBuffer return array_vec; } +private: + //! Compute the next representable value of `x1` in the direction of `x2` for a + //! real-valued scalar type (`APyFloat` or `APyFixed`). + template + static REAL_SCALAR_TYPE + real_nextafter(const REAL_SCALAR_TYPE& x1, const REAL_SCALAR_TYPE& x2) + { + if (x1 < x2) { + return x1.next_up(); + } else if (x2 < x1) { + return x1.next_down(); + } else { + return x2; + } + } + +public: + //! Compute the next representable value of `x1` in the direction of `x2`, + //! element-wise, broadcasting `x1` and `x2` to a common shape. + static ARRAY_TYPE nextafter(ARRAY_TYPE x1, ARRAY_TYPE x2) + { + using SCALAR_TYPE = scalar_variant_t; + + const auto broadcast_shape = smallest_broadcastable_shape(x1._shape, x2._shape); + x1 = x1.broadcast_to(broadcast_shape); + x2 = x2.broadcast_to(broadcast_shape); + + ARRAY_TYPE result = x1.create_array(broadcast_shape); + SCALAR_TYPE sx1 = x1.create_scalar(); + SCALAR_TYPE sx2 = x2.create_scalar(); + SCALAR_TYPE sres = x1.create_scalar(); + + for (std::size_t i = 0; i < result._nitems; ++i) { + sx1.copy_n_from(std::begin(x1._data) + i * x1._itemsize, x1._itemsize); + sx2.copy_n_from(std::begin(x2._data) + i * x2._itemsize, x2._itemsize); + + sres = real_nextafter(sx1, sx2); + + sres.copy_n_to( + std::begin(result._data) + i * result._itemsize, result._itemsize + ); + } + + return result; + } + /* ****************************************************************************** * * * Array folding methods * * * ****************************************************************************** */ diff --git a/src/apyfixedarray_wrapper.cc b/src/apyfixedarray_wrapper.cc index c5416c4c3..16b4d0e22 100644 --- a/src/apyfixedarray_wrapper.cc +++ b/src/apyfixedarray_wrapper.cc @@ -1834,6 +1834,9 @@ void bind_fixed_array(nb::module_& m) [6, 6, 6]], int_bits=5, frac_bits=0) )pbdoc" ) + .def_static( + "_nextafter", &APyFixedArray::nextafter, nb::arg("x1"), nb::arg("x2") + ) /* * Dunder methods diff --git a/src/apyfloatarray_wrapper.cc b/src/apyfloatarray_wrapper.cc index ba2bad6a7..9f7ce9a79 100644 --- a/src/apyfloatarray_wrapper.cc +++ b/src/apyfloatarray_wrapper.cc @@ -1070,6 +1070,9 @@ void bind_float_array(nb::module_& m) [6, 6, 6]], exp_bits=5, man_bits=10) )pbdoc" ) + .def_static( + "_nextafter", &APyFloatArray::nextafter, nb::arg("x1"), nb::arg("x2") + ) /* * Dunder methods From 72ddf0eba1d3e9296fa681377115eb5179eeeac5 Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Wed, 28 Oct 2026 09:01:00 +0100 Subject: [PATCH 03/18] Improve docs for next_up/down --- docs/api/apyfixed.rst | 4 +++ docs/api/apyfixedarray.rst | 4 +++ lib/apytypes/_apytypes.pyi | 60 +++++++++++++++++++++++++++++++++--- src/apyfixed.h | 2 ++ src/apyfixed_wrapper.cc | 34 ++++++++++++++++++-- src/apyfixedarray.h | 2 ++ src/apyfixedarray_wrapper.cc | 34 ++++++++++++++++++-- 7 files changed, 132 insertions(+), 8 deletions(-) diff --git a/docs/api/apyfixed.rst b/docs/api/apyfixed.rst index 88033c36a..c1d753618 100644 --- a/docs/api/apyfixed.rst +++ b/docs/api/apyfixed.rst @@ -41,6 +41,10 @@ .. automethod:: copy + .. automethod:: next_up + + .. automethod:: next_down + Properties ---------- diff --git a/docs/api/apyfixedarray.rst b/docs/api/apyfixedarray.rst index 703fdc1c4..f4cfb5b84 100644 --- a/docs/api/apyfixedarray.rst +++ b/docs/api/apyfixedarray.rst @@ -85,6 +85,10 @@ .. automethod:: min + .. automethod:: next_up + + .. automethod:: next_down + .. automethod:: outer Broadcasting diff --git a/lib/apytypes/_apytypes.pyi b/lib/apytypes/_apytypes.pyi index fc052e9f5..2e928dd7e 100644 --- a/lib/apytypes/_apytypes.pyi +++ b/lib/apytypes/_apytypes.pyi @@ -4810,8 +4810,34 @@ class APyFixed: """ def __abs__(self) -> APyFixed: ... - def next_up(self) -> APyFixed: ... - def next_down(self) -> APyFixed: ... + def next_up(self) -> APyFixed: + """ + Return the next representable fixed-point number in the same format. + + The word length is not increased. At the maximum representable value, + the result is unchanged: the operation saturates instead of wrapping. + + .. versionadded:: 0.6 + + Returns + ------- + :class:`APyFixed` + """ + + def next_down(self) -> APyFixed: + """ + Return the previous representable fixed-point number in the same format. + + The word length is not increased. At the minimum representable value, + the result is unchanged: the operation saturates instead of wrapping. + + .. versionadded:: 0.6 + + Returns + ------- + :class:`APyFixed` + """ + def __float__(self) -> float: ... def __repr__(self) -> str: ... def __str__(self, base: int = 10) -> str: ... @@ -6343,8 +6369,34 @@ class APyFixedArray: def __matmul__(self, rhs: APyCFixedArray) -> APyCFixedArray | APyCFixed: ... def __repr__(self) -> str: ... def __abs__(self) -> APyFixedArray: ... - def next_up(self) -> APyFixedArray: ... - def next_down(self) -> APyFixedArray: ... + def next_up(self) -> APyFixedArray: + """ + Return the next representable value of each element in the same format. + + The word length is not increased. Elements at the maximum representable + value remain unchanged: the operation saturates instead of wrapping. + + .. versionadded:: 0.6 + + Returns + ------- + :class:`APyFixedArray` + """ + + def next_down(self) -> APyFixedArray: + """ + Return the previous representable value of each element in the same format. + + The word length is not increased. Elements at the minimum representable + value remain unchanged: the operation saturates instead of wrapping. + + .. versionadded:: 0.6 + + Returns + ------- + :class:`APyFixedArray` + """ + def __str__(self, base: int = 10) -> str: ... def __getitem__( self, diff --git a/src/apyfixed.h b/src/apyfixed.h index 54c8deaac..498a03572 100644 --- a/src/apyfixed.h +++ b/src/apyfixed.h @@ -262,9 +262,11 @@ class APyFixed { apy_limb_t increment_lsb() noexcept; //! Get the next representable fixed-point number in the same format. + //! The word length is unchanged. Saturates at the maximum instead of wrapping. APyFixed next_up() const; //! Get the previous representable fixed-point number in the same format. + //! The word length is unchanged. Saturates at the minimum instead of wrapping. APyFixed next_down() const; //! Convert the underlying bit pattern to a Python long integer diff --git a/src/apyfixed_wrapper.cc b/src/apyfixed_wrapper.cc index ffc75e859..04d16770f 100644 --- a/src/apyfixed_wrapper.cc +++ b/src/apyfixed_wrapper.cc @@ -556,8 +556,38 @@ void bind_fixed(nb::module_& m) * Dunder methods */ .def("__abs__", &APyFixed::abs) - .def("next_up", &APyFixed::next_up) - .def("next_down", &APyFixed::next_down) + .def( + "next_up", + &APyFixed::next_up, + R"pbdoc( + Return the next representable fixed-point number in the same format. + + The word length is not increased. At the maximum representable value, + the result is unchanged: the operation saturates instead of wrapping. + + .. versionadded:: 0.6 + + Returns + ------- + :class:`APyFixed` + )pbdoc" + ) + .def( + "next_down", + &APyFixed::next_down, + R"pbdoc( + Return the previous representable fixed-point number in the same format. + + The word length is not increased. At the minimum representable value, + the result is unchanged: the operation saturates instead of wrapping. + + .. versionadded:: 0.6 + + Returns + ------- + :class:`APyFixed` + )pbdoc" + ) .def("__float__", &APyFixed::operator double) .def("__repr__", &APyFixed::repr) .def("__str__", &APyFixed::to_string, nb::arg("base") = 10) diff --git a/src/apyfixedarray.h b/src/apyfixedarray.h index e136e1aad..2f35314d2 100644 --- a/src/apyfixedarray.h +++ b/src/apyfixedarray.h @@ -294,9 +294,11 @@ class APyFixedArray : public APyArray { APyFixedArray abs() const; //! Elementwise next representable value in the same format. + //! The word length is unchanged. Saturates at the maximum instead of wrapping. APyFixedArray next_up() const; //! Elementwise previous representable value in the same format. + //! The word length is unchanged. Saturates at the minimum instead of wrapping. APyFixedArray next_down() const; /*! diff --git a/src/apyfixedarray_wrapper.cc b/src/apyfixedarray_wrapper.cc index 16b4d0e22..14fcc829a 100644 --- a/src/apyfixedarray_wrapper.cc +++ b/src/apyfixedarray_wrapper.cc @@ -1857,8 +1857,38 @@ void bind_fixed_array(nb::module_& m) ) .def("__repr__", &APyFixedArray::repr) .def("__abs__", &APyFixedArray::abs) - .def("next_up", &APyFixedArray::next_up) - .def("next_down", &APyFixedArray::next_down) + .def( + "next_up", + &APyFixedArray::next_up, + R"pbdoc( + Return the next representable value of each element in the same format. + + The word length is not increased. Elements at the maximum representable + value remain unchanged: the operation saturates instead of wrapping. + + .. versionadded:: 0.6 + + Returns + ------- + :class:`APyFixedArray` + )pbdoc" + ) + .def( + "next_down", + &APyFixedArray::next_down, + R"pbdoc( + Return the previous representable value of each element in the same format. + + The word length is not increased. Elements at the minimum representable + value remain unchanged: the operation saturates instead of wrapping. + + .. versionadded:: 0.6 + + Returns + ------- + :class:`APyFixedArray` + )pbdoc" + ) .def("__str__", &APyFixedArray::to_string, nb::arg("base") = 10) // Iteration and friends From 3acea024df721e21f5e1c579c21b983afb5714b1 Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Wed, 28 Oct 2026 14:04:16 +0100 Subject: [PATCH 04/18] Simplify nextafter --- lib/apytypes/_array_functions.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/lib/apytypes/_array_functions.py b/lib/apytypes/_array_functions.py index 27c742b0c..d0743828e 100644 --- a/lib/apytypes/_array_functions.py +++ b/lib/apytypes/_array_functions.py @@ -2863,7 +2863,6 @@ def nextafter( ) -> APyFloatArray | APyFixedArray: """ Return the next representable value of `x1` in the direction of `x2`, element-wise. - `x1` and `x2` do not need to be of the same type. If `x1.shape` != `x2.shape`, they must be broadcastable to a common shape (which becomes the shape of the output). @@ -2884,11 +2883,6 @@ def nextafter( if not isinstance(x1, APyFloatArray | APyFixedArray): raise TypeError(f"nextafter: x1 must be a real APyArray, got {type(x1)}") - try: - nextafter_impl = x1._nextafter - except AttributeError: - raise TypeError(f"Type {type(x1)} has no attribute `_nextafter`") - if type(x2) is not type(x1): if isinstance(x2, int | float | APyFixed | APyFloat): if isinstance(x1, APyFixedArray): @@ -2905,7 +2899,7 @@ def nextafter( f"`int`, `float`, `APyFixed`, `APyFloat`, got {type(x2)}" ) - return nextafter_impl(x1, x2) + return x1._nextafter(x1, x2) # ============================================================================= From bd61bb282e6dc3eaf65fe34d94515b28bf329f54 Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Wed, 28 Oct 2026 16:51:07 +0100 Subject: [PATCH 05/18] Update pinned pytest version for benchmarks --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 9c9251b04..18f924ba5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,7 @@ docs = [ test = ["numpy>=2", "pytest>=8.2"] test_hdl = ["numpy>=2", "pytest>=8.2", "cocotb>=2", "vunit-hdl", "packaging"] dev = ["nanobind>=3"] -benchmark = ["numpy>=2", "pytest>=8.2", "pytest-benchmark"] +benchmark = ["numpy>=2", "pytest>=8.2,<9.2", "pytest-benchmark"] comparison = [ "fpbinary", "fixedpoint", From 43cf2f10a5cefffbbea23dcc500756e964dbebab Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Thu, 29 Oct 2026 09:57:56 +0100 Subject: [PATCH 06/18] Improve nextafter --- lib/apytypes/_array_functions.py | 37 +++++++-------- lib/test/test_array_functions.py | 80 +++++++++++++++++++++++--------- src/apyarray.h | 4 +- 3 files changed, 77 insertions(+), 44 deletions(-) diff --git a/lib/apytypes/_array_functions.py b/lib/apytypes/_array_functions.py index d0743828e..7294846f5 100644 --- a/lib/apytypes/_array_functions.py +++ b/lib/apytypes/_array_functions.py @@ -2848,18 +2848,14 @@ def outer(a: APyArray, b: APyArray) -> APyArray: @overload -def nextafter( - x1: APyFloatArray, x2: APyFloatArray | APyFloat | float | int -) -> APyFloatArray: ... +def nextafter(x1: APyFloatArray, x2: APyFloatArray | APyFloat) -> APyFloatArray: ... @overload -def nextafter( - x1: APyFixedArray, x2: APyFixedArray | APyFixed | float | int -) -> APyFixedArray: ... +def nextafter(x1: APyFixedArray, x2: APyFixedArray | APyFixed) -> APyFixedArray: ... def nextafter( x1: APyFloatArray | APyFixedArray, - x2: APyFloatArray | APyFixedArray | APyFloat | APyFixed | float | int, + x2: APyFloatArray | APyFixedArray | APyFloat | APyFixed, ) -> APyFloatArray | APyFixedArray: """ Return the next representable value of `x1` in the direction of `x2`, element-wise. @@ -2872,7 +2868,7 @@ def nextafter( ---------- x1 : :class:`APyFloatArray` or :class:`APyFixedArray` Values to get the next representable value of. - x2 : :class:`APyFloatArray`, :class:`APyFixedArray`, :class:`APyFixed`, :class:`APyFloat`, :class:`int`, or :class:`float` + x2 : :class:`APyFloatArray`, :class:`APyFixedArray`, :class:`APyFixed`, or :class:`APyFloat` Direction in which to get the next representable value. Returns @@ -2883,21 +2879,20 @@ def nextafter( if not isinstance(x1, APyFloatArray | APyFixedArray): raise TypeError(f"nextafter: x1 must be a real APyArray, got {type(x1)}") - if type(x2) is not type(x1): - if isinstance(x2, int | float | APyFixed | APyFloat): - if isinstance(x1, APyFixedArray): - x2 = type(x1).from_float( - [x2], int_bits=x1.int_bits, frac_bits=x1.frac_bits - ) - else: - x2 = type(x1).from_float( - [x2], exp_bits=x1.exp_bits, man_bits=x1.man_bits, bias=x1.bias - ) - else: + if isinstance(x1, APyFixedArray): + if not isinstance(x2, APyFixedArray | APyFixed): raise TypeError( - "nextafter: x2 must be an array of the same type as x1, or one of " - f"`int`, `float`, `APyFixed`, `APyFloat`, got {type(x2)}" + "nextafter: x2 must be APyFixedArray or APyFixed when x1 is " + f"APyFixedArray, got {type(x2)}" ) + elif not isinstance(x2, APyFloatArray | APyFloat): + raise TypeError( + "nextafter: x2 must be APyFloatArray or APyFloat when x1 is " + f"APyFloatArray, got {type(x2)}" + ) + + if isinstance(x2, APyFixed | APyFloat): + x2 = type(x1).from_float([x2], spec=x2) return x1._nextafter(x1, x2) diff --git a/lib/test/test_array_functions.py b/lib/test/test_array_functions.py index 6628a974a..613fdf9a3 100644 --- a/lib/test/test_array_functions.py +++ b/lib/test/test_array_functions.py @@ -563,13 +563,31 @@ def test_nextafter_float_array_elementwise(): assert y[2].is_identical(x2[2]) +@pytest.mark.parametrize("array_type", [APyFloatArray, APyFixedArray]) +@pytest.mark.parametrize( + ("start_format", "direction_format"), + [((5, 2), (6, 10)), ((6, 10), (5, 2))], +) +def test_nextafter_equal_values_different_formats( + array_type, start_format, direction_format +): + x1 = array_type.from_float([1.0, 1.25, 0.75], *start_format) + x2 = array_type.from_float([1.0, 1.25, 0.75], *direction_format) + + assert nextafter(x1, x2).is_identical(x1) + + @pytest.mark.parametrize("start_sign", [0, 1]) @pytest.mark.parametrize("direction_sign", [0, 1]) -def test_nextafter_float_array_signed_zero(start_sign, direction_sign): +@pytest.mark.parametrize("scalar_direction", [False, True]) +def test_nextafter_float_array_signed_zero( + start_sign, direction_sign, scalar_direction +): x1 = APyFloatArray([start_sign], [0], [0], exp_bits=5, man_bits=10) x2 = APyFloatArray([direction_sign], [0], [0], exp_bits=5, man_bits=10) + direction = x2[0].cast(exp_bits=6, man_bits=11, bias=17) if scalar_direction else x2 - assert nextafter(x1, x2).is_identical(x2) + assert nextafter(x1, direction).is_identical(x2) def test_nextafter_float_array_broadcasting(): @@ -630,36 +648,54 @@ def test_nextafter_complex_fixed_array_raises(): def test_nextafter_complex_direction_raises(array_type, direction): x1 = array_type.from_float([1.0], 5, 10) - with pytest.raises( - TypeError, match="nextafter: x2 must be an array of the same type as x1" - ): + with pytest.raises(TypeError, match="nextafter: x2 must be"): _ = nextafter(x1, direction) -@pytest.mark.parametrize("array_type", [APyFloatArray, APyFixedArray]) @pytest.mark.parametrize( - "direction", - [ - 2, - 2.0, - APyFloat.from_float(2.0, exp_bits=5, man_bits=10), - APyFixed.from_float(2.0, int_bits=6, frac_bits=4), - ], + ("array_type", "scalar_type"), + [(APyFloatArray, APyFloat), (APyFixedArray, APyFixed)], ) -def test_nextafter_real_direction(array_type, direction): +@pytest.mark.parametrize("value", [2.0, 1.0625, 0.9375, 1.0]) +def test_nextafter_real_direction(array_type, scalar_type, value): + x1 = array_type.from_float([1.0, 1.25, 0.75], 5, 2) + direction = scalar_type.from_float(value, 6, 10) + + result = nextafter(x1, direction) + + assert result.shape == x1.shape + for start, actual in zip(x1, result): + if start < direction: + assert actual.is_identical(start.next_up()) + elif direction < start: + assert actual.is_identical(start.next_down()) + else: + assert actual.is_identical(start) + + +@pytest.mark.parametrize("array_type", [APyFloatArray, APyFixedArray]) +@pytest.mark.parametrize("direction", [2, 2.0]) +def test_nextafter_python_direction_raises(array_type, direction): x1 = array_type.from_float([1.0], 5, 10) - assert nextafter(x1, direction).is_identical(x1.next_up()) + with pytest.raises(TypeError, match="nextafter: x2 must be"): + _ = nextafter(x1, direction) -def test_nextafter_type_raises(): - fp = APyFloatArray.from_float([1.0], exp_bits=5, man_bits=10) - fx = APyFixedArray.from_float([1.0], int_bits=5, frac_bits=5) +@pytest.mark.parametrize( + ("array_type", "direction"), + [ + (APyFloatArray, APyFixed.from_float(2.0, int_bits=6, frac_bits=4)), + (APyFixedArray, APyFloat.from_float(2.0, exp_bits=5, man_bits=10)), + (APyFloatArray, APyFixedArray.from_float([2.0], int_bits=6, frac_bits=4)), + (APyFixedArray, APyFloatArray.from_float([2.0], exp_bits=5, man_bits=10)), + ], +) +def test_nextafter_type_raises(array_type, direction): + x1 = array_type.from_float([1.0], 5, 10) - with pytest.raises( - TypeError, match="nextafter: x2 must be an array of the same type as x1" - ): - _ = nextafter(fp, fx) + with pytest.raises(TypeError, match="nextafter: x2 must be"): + _ = nextafter(x1, direction) @pytest.mark.parametrize("shape", [(i, j) for i in range(1, 5) for j in range(1, 5)]) diff --git a/src/apyarray.h b/src/apyarray.h index 4a7cfde94..922628d59 100644 --- a/src/apyarray.h +++ b/src/apyarray.h @@ -1287,8 +1287,10 @@ template class APyArray : public APyBuffer return x1.next_up(); } else if (x2 < x1) { return x1.next_down(); + } else if constexpr (std::is_same_v) { + return x2.cast(x1.get_exp_bits(), x1.get_man_bits(), x1.get_bias()); } else { - return x2; + return x1; } } From e691744aa3fa8146f40538275e88a9ae0bab2a5c Mon Sep 17 00:00:00 2001 From: Oscar Gustafsson Date: Mon, 26 Oct 2026 14:32:58 +0100 Subject: [PATCH 07/18] Bump scala to 2.13.18 --- lib/test/test_codegen.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/test/test_codegen.py b/lib/test/test_codegen.py index 9c76db3e1..c9ce0a002 100644 --- a/lib/test/test_codegen.py +++ b/lib/test/test_codegen.py @@ -200,7 +200,7 @@ def test_generate_rom_chisel(table, address, input_register, output_register, tm str(filepath), "--server=false", "--scala", - "2.13.12", + "2.13.18", "--dependency", "org.chipsalliance::chisel:6.5.0", ], @@ -261,7 +261,7 @@ def test_generate_rom_spinalhdl( str(filepath), "--server=false", "--scala", - "2.13.12", + "2.13.18", "--dependency", "com.github.spinalhdl::spinalhdl-core:1.10.2", ], From 23d20f45df287284d6ef7a8b5e3a8b1385385959 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:21:40 +0000 Subject: [PATCH 08/18] [pre-commit.ci] pre-commit autoupdate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/igorshubovych/markdownlint-cli: v0.49.1 → v0.50.0](https://github.com/igorshubovych/markdownlint-cli/compare/v0.49.1...v0.50.0) - [github.com/astral-sh/ruff-pre-commit: v0.17.1 → v0.17.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.17.1...v0.17.2) --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index defd317ad..73edca185 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -20,7 +20,7 @@ repos: hooks: - id: clang-format - repo: https://github.com/igorshubovych/markdownlint-cli - rev: v0.49.1 + rev: v0.50.0 hooks: - id: markdownlint - repo: https://github.com/pre-commit/pygrep-hooks @@ -34,7 +34,7 @@ repos: - id: text-unicode-replacement-char - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.17.1 + rev: v0.17.2 hooks: # Run the linter. - id: ruff From 415cd27622b936f9373636fbe102e77e2be50979 Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Tue, 27 Oct 2026 18:06:32 +0100 Subject: [PATCH 09/18] Fix cancellation bug for floating-point --- CHANGELOG.md | 1 + lib/test/apyfloat/test_arithmetic.py | 66 ++++++++++++++++++++++++++++ src/apyfloat_util.h | 34 +++++++------- 3 files changed, 84 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e7acfbdd2..ff271f020 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 documentation for exact expressions. - Bug in floating-point cast for values between the largest subnormal and the smallest normal value of the destination format. +- Bug in floating-point addition for cancellation involving mixed biases. ### Changed diff --git a/lib/test/apyfloat/test_arithmetic.py b/lib/test/apyfloat/test_arithmetic.py index 011d54de3..00efb5a68 100644 --- a/lib/test/apyfloat/test_arithmetic.py +++ b/lib/test/apyfloat/test_arithmetic.py @@ -124,6 +124,72 @@ def test_add_subnormals(apyfloat: type[APyCFloat]): assert res.is_identical(apyfloat(0, 7, 0, 4, 3)) +@pytest.mark.float_add +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize("man_bits", [17, 61]) +@pytest.mark.parametrize( + ("lhs_bias", "rhs_bias", "result_bias"), [(14, 15, 14), (10, 15, 12)] +) +def test_add_general_aligned_cancellation_both_subnormal( + apyfloat: type[APyFloat | APyCFloat], + man_bits: int, + lhs_bias: int, + rhs_bias: int, + result_bias: int, +): + bias_delta = rhs_bias - lhs_bias + lhs = apyfloat(0, 0, 1 << (man_bits - 1 - bias_delta), 5, man_bits, bias=lhs_bias) + rhs = apyfloat(1, 0, 1 << (man_bits - 1), 5, man_bits, bias=rhs_bias) + zero = apyfloat(0, 0, 0, 5, man_bits, bias=result_bias) + + assert (lhs + rhs).is_identical(zero) + assert (rhs + lhs).is_identical(zero) + + +@pytest.mark.float_add +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize("man_bits", [17, 61]) +@pytest.mark.parametrize( + ("lhs_bias", "rhs_bias", "result_bias"), [(14, 15, 14), (10, 15, 12)] +) +def test_add_general_aligned_cancellation_one_subnormal( + apyfloat: type[APyFloat | APyCFloat], + man_bits: int, + lhs_bias: int, + rhs_bias: int, + result_bias: int, +): + bias_delta = rhs_bias - lhs_bias + lhs = apyfloat(0, 0, 1 << (man_bits - bias_delta), 5, man_bits, bias=lhs_bias) + rhs = apyfloat(1, 1, 0, 5, man_bits, bias=rhs_bias) + zero = apyfloat(0, 0, 0, 5, man_bits, bias=result_bias) + + assert (lhs + rhs).is_identical(zero) + assert (rhs + lhs).is_identical(zero) + + +@pytest.mark.float_add +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize("man_bits", [17, 61]) +@pytest.mark.parametrize( + ("lhs_bias", "rhs_bias", "result_bias"), [(14, 15, 14), (10, 15, 12)] +) +def test_add_general_aligned_cancellation_both_normal( + apyfloat: type[APyFloat | APyCFloat], + man_bits: int, + lhs_bias: int, + rhs_bias: int, + result_bias: int, +): + bias_delta = rhs_bias - lhs_bias + lhs = apyfloat(0, 1, 1 << (man_bits - 1), 5, man_bits, bias=lhs_bias) + rhs = apyfloat(1, 1 + bias_delta, 1 << (man_bits - 1), 5, man_bits, bias=rhs_bias) + zero = apyfloat(0, 0, 0, 5, man_bits, bias=result_bias) + + assert (lhs + rhs).is_identical(zero) + assert (rhs + lhs).is_identical(zero) + + @pytest.mark.float_add @pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) @pytest.mark.parametrize("exp", [0, 3, 14, 17]) diff --git a/src/apyfloat_util.h b/src/apyfloat_util.h index 4ba4df0c0..7c0fb6550 100644 --- a/src/apyfloat_util.h +++ b/src/apyfloat_util.h @@ -1182,9 +1182,9 @@ template auto [src1_pure_exp, src1_bw] = pure_exp(src1, src1_spec); auto [src2_pure_exp, src2_bw] = pure_exp(src2, src2_spec); if (src1_pure_exp == src2_pure_exp) { - std::uint64_t n1_man = src1.man << (_MAN_T_SIZE_BITS - src1_bw); - std::uint64_t n2_man = src2.man << (_MAN_T_SIZE_BITS - src2_bw); - return n1_man < n2_man; + man_t src1_man = true_man(src1, src1_spec) << (_MAN_T_SIZE_BITS - src1_bw); + man_t src2_man = true_man(src2, src2_spec) << (_MAN_T_SIZE_BITS - src2_bw); + return src1_man < src2_man; } else { return src1_pure_exp < src2_pure_exp; } @@ -1381,6 +1381,13 @@ template < return; } + // Check cancellation. Since we know |x|>= |y|, entering here means same magnitude + if (!same_sign && !floating_point_less_than_abs(y, y_spec, x, x_spec)) { + const man_t res_man = qntz == QuantizationMode::JAM ? 1 : 0; + z = { qntz == QuantizationMode::TRN, 0, res_man }; + return; + } + APyFloatData x_wide = x_spec == dst_spec ? x : floating_point_cast_no_quant_no_max_exp( x, x_spec.man_bits, dst_spec.man_bits @@ -1426,14 +1433,7 @@ template < } else if (new_man & RES_LO) { new_man <<= 1; } else { - if (exp_delta == 0 && !same_sign && x_wide.man == y_wide.man) { - man_t res_man = qntz == QuantizationMode::JAM ? 1 : 0; - bool res_sign = qntz == QuantizationMode::TRN; - z = { res_sign, 0, res_man }; - return; - } - - // Cancellation or addition with subnormals. Mantissa should be shifted + // Mantissa should be shifted // until 1.xx is obtained or new_exp equals 0. const unsigned man_leading_zeros = leading_zeros(new_man); const unsigned shift = man_leading_zeros - NORMALIZATION_CONST; @@ -1512,6 +1512,12 @@ template < return; } + if (!same_sign && !floating_point_less_than_abs(y, y_spec, x, x_spec)) { + const man_t res_man = qntz == QuantizationMode::JAM ? 1 : 0; + z = { qntz == QuantizationMode::TRN, 0, res_man }; + return; + } + APyFloatData x_wide = x_spec == dst_spec ? x : floating_point_cast_no_quant_no_max_exp( x, x_spec.man_bits, dst_spec.man_bits @@ -1525,12 +1531,6 @@ template < const std::int64_t y_true_exp = true_exp(y_wide, y_spec.bias); const std::uint64_t exp_delta = x_true_exp - y_true_exp; - if (exp_delta == 0 && !same_sign && x_wide.man == y_wide.man) { - man_t res_man = qntz == QuantizationMode::JAM ? 1 : 0; - z = { qntz == QuantizationMode::TRN, 0, res_man }; - return; - } - exp_t new_exp = x_true_exp + dst_spec.bias; if (new_exp > RES_MAX_EXP) { const exp_t exp = int(new_exp) < 0 ? 0 : RES_MAX_EXP; From 2cc9a4102107c66736a5135b74f702bc96b95303 Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Thu, 29 Oct 2026 11:34:58 +0100 Subject: [PATCH 10/18] Fix mixed-format fp addition for subnormals --- CHANGELOG.md | 1 + lib/test/apyfloat/test_arithmetic.py | 15 ++++++++ src/apyfloat_util.h | 57 ++++++---------------------- 3 files changed, 28 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff271f020..26c5e0447 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Bug in floating-point cast for values between the largest subnormal and the smallest normal value of the destination format. - Bug in floating-point addition for cancellation involving mixed biases. +- Bug in floating-point addition with mixed formats for subnormals. ### Changed diff --git a/lib/test/apyfloat/test_arithmetic.py b/lib/test/apyfloat/test_arithmetic.py index 00efb5a68..5fe64b4af 100644 --- a/lib/test/apyfloat/test_arithmetic.py +++ b/lib/test/apyfloat/test_arithmetic.py @@ -124,6 +124,21 @@ def test_add_subnormals(apyfloat: type[APyCFloat]): assert res.is_identical(apyfloat(0, 7, 0, 4, 3)) +@pytest.mark.float_add +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize("man_bits", [5, 61]) +def test_add_subnormal_widening_same_bias( + apyfloat: type[APyFloat | APyCFloat], man_bits: int +): + lhs = apyfloat(0, 0, 1, exp_bits=5, man_bits=3) + rhs = apyfloat(0, 0, 0, exp_bits=5, man_bits=man_bits) + expected = apyfloat(0, 0, 1 << (man_bits - 3), exp_bits=5, man_bits=man_bits) + + assert (lhs + rhs).is_identical(expected) + assert (rhs + lhs).is_identical(expected) + assert lhs == expected + + @pytest.mark.float_add @pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) @pytest.mark.parametrize("man_bits", [17, 61]) diff --git a/src/apyfloat_util.h b/src/apyfloat_util.h index 7c0fb6550..245714c47 100644 --- a/src/apyfloat_util.h +++ b/src/apyfloat_util.h @@ -711,40 +711,15 @@ template return { src.sign, exp_t(new_exp), new_man }; } -//! Cast a floating-point number when it is known that no quantization happens and that -//! the exponent is not max. In addition, src_spec.bias = dst_spec.bias. -[[maybe_unused]] static APY_INLINE APyFloatData floating_point_cast_no_quant_no_max_exp( +//! Widen a floating-point mantissa without changing the sign or exponent. +//! Assumes equal biases, a non-max exponent, and dst_man_bits >= src_man_bits. +[[maybe_unused]] static APY_INLINE APyFloatData widening_man( const APyFloatData& src, const std::uint8_t src_man_bits, const std::uint8_t dst_man_bits ) { - // Adjust the exponent and mantissa if converting from a subnormal - man_t new_man; - std::int64_t new_exp; - if (src.exp == 0) { - if (src.man == 0) { - return { src.sign, 0, 0 }; - } - const exp_t subn_adjustment = count_trailing_bits(src.man); - const std::int64_t left_shift_amount = src_man_bits - subn_adjustment; - if (1 < left_shift_amount) { - // The result remains subnormal - new_man = src.man << 1; - new_exp = 0; - } else { - // The result becomes normal - new_man = src.man << left_shift_amount; - new_man &= (1ULL << src_man_bits) - 1; - new_exp = std::int64_t(1) - left_shift_amount; - } - } else { - new_man = src.man; - new_exp = std::int64_t(src.exp); - } - - new_man <<= dst_man_bits - src_man_bits; - return { src.sign, exp_t(new_exp), new_man }; + return { src.sign, src.exp, src.man << (dst_man_bits - src_man_bits) }; } //! Cast a floating-point number when it is known that no quantization happens @@ -1388,14 +1363,10 @@ template < return; } - APyFloatData x_wide = x_spec == dst_spec ? x - : floating_point_cast_no_quant_no_max_exp( - x, x_spec.man_bits, dst_spec.man_bits - ); - APyFloatData y_wide = y_spec == dst_spec ? y - : floating_point_cast_no_quant_no_max_exp( - y, y_spec.man_bits, dst_spec.man_bits - ); + APyFloatData x_wide + = x_spec == dst_spec ? x : widening_man(x, x_spec.man_bits, dst_spec.man_bits); + APyFloatData y_wide + = y_spec == dst_spec ? y : widening_man(y, y_spec.man_bits, dst_spec.man_bits); // Tentative exponent exp_t x_true_exp = true_exp(x_wide, x_spec.bias); @@ -1518,14 +1489,10 @@ template < return; } - APyFloatData x_wide = x_spec == dst_spec ? x - : floating_point_cast_no_quant_no_max_exp( - x, x_spec.man_bits, dst_spec.man_bits - ); - APyFloatData y_wide = y_spec == dst_spec ? y - : floating_point_cast_no_quant_no_max_exp( - y, y_spec.man_bits, dst_spec.man_bits - ); + APyFloatData x_wide + = x_spec == dst_spec ? x : widening_man(x, x_spec.man_bits, dst_spec.man_bits); + APyFloatData y_wide + = y_spec == dst_spec ? y : widening_man(y, y_spec.man_bits, dst_spec.man_bits); const std::int64_t x_true_exp = true_exp(x_wide, x_spec.bias); const std::int64_t y_true_exp = true_exp(y_wide, y_spec.bias); From cf4fec55e9ef0410b21a5ce15f83ea4a9d2cbcbd Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Fri, 30 Oct 2026 09:34:09 +0100 Subject: [PATCH 11/18] Fix floating-point addition and subtraction with mixed biases --- CHANGELOG.md | 5 +- lib/test/apyfloat/test_arithmetic.py | 70 +++++++++++++++++++++++++++- lib/test/apyfloat/test_rounding.py | 45 ++++++++++++++++++ src/apyfloat_util.h | 29 +++++++----- 4 files changed, 133 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26c5e0447..c3d63dcc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,10 +37,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `APyFixedArray.to_bits` for 64-bit NumPy arrays on 32-bit systems. - `prod` and `cumprod` are using fewer bits for fixed-point arrays, see the documentation for exact expressions. -- Bug in floating-point cast for values between the largest subnormal and +- Floating-point cast for values between the largest subnormal and the smallest normal value of the destination format. -- Bug in floating-point addition for cancellation involving mixed biases. -- Bug in floating-point addition with mixed formats for subnormals. +- Floating-point addition with mixed formats. ### Changed diff --git a/lib/test/apyfloat/test_arithmetic.py b/lib/test/apyfloat/test_arithmetic.py index 5fe64b4af..6768efe6c 100644 --- a/lib/test/apyfloat/test_arithmetic.py +++ b/lib/test/apyfloat/test_arithmetic.py @@ -136,7 +136,75 @@ def test_add_subnormal_widening_same_bias( assert (lhs + rhs).is_identical(expected) assert (rhs + lhs).is_identical(expected) - assert lhs == expected + + +@pytest.mark.float_add +def test_add_negative_exponent_delta_short(): + for apyfloat in (APyFloat, APyCFloat): + lhs = apyfloat(0, 2, 0, 5, 17, bias=16) + rhs = apyfloat(0, 0, 1, 5, 17, bias=14) + expected = apyfloat(0, 1, 2, 5, 17, bias=15) + + assert (lhs + rhs).is_identical(expected) + assert (rhs + lhs).is_identical(expected) + + +@pytest.mark.float_sub +def test_sub_negative_exponent_delta_short(): + for apyfloat in (APyFloat, APyCFloat): + lhs = apyfloat(0, 2, 0, 5, 17, bias=16) + rhs = apyfloat(0, 0, 1, 5, 17, bias=14) + expected = apyfloat(0, 0, (1 << 17) - 2, 5, 17, bias=15) + + assert (lhs - rhs).is_identical(expected) + assert (rhs - lhs).is_identical(apyfloat(1, 0, (1 << 17) - 2, 5, 17, bias=15)) + + +@pytest.mark.float_add +def test_add_negative_exponent_delta_general(): + for apyfloat in (APyFloat, APyCFloat): + lhs = apyfloat(0, 2, 0, 5, 61, bias=16) + rhs = apyfloat(0, 0, 1, 5, 61, bias=14) + expected = apyfloat(0, 1, 2, 5, 61, bias=15) + + assert (lhs + rhs).is_identical(expected) + assert (rhs + lhs).is_identical(expected) + + +@pytest.mark.float_sub +def test_sub_negative_exponent_delta_general(): + for apyfloat in (APyFloat, APyCFloat): + lhs = apyfloat(0, 2, 0, 5, 61, bias=16) + rhs = apyfloat(0, 0, 1, 5, 61, bias=14) + expected = apyfloat(0, 0, (1 << 61) - 2, 5, 61, bias=15) + reverse = apyfloat(1, 0, (1 << 61) - 2, 5, 61, bias=15) + + assert (lhs - rhs).is_identical(expected) + assert (rhs - lhs).is_identical(reverse) + + +@pytest.mark.float_add +def test_add_larger_negative_exponent_delta(): + for apyfloat in (APyFloat, APyCFloat): + for man_bits in (17, 61): + lhs = apyfloat(0, 3, 0, 5, man_bits, bias=16) + rhs = apyfloat(0, 0, 1, 5, man_bits, bias=12) + expected = apyfloat(0, 1, 4, 5, man_bits, bias=14) + + assert (lhs + rhs).is_identical(expected) + assert (rhs + lhs).is_identical(expected) + + +@pytest.mark.float_add +def test_add_nonpositive_tentative_exponent_carry(): + for apyfloat in (APyFloat, APyCFloat): + for man_bits in (17, 61): + lhs = apyfloat(0, 1, 1 << (man_bits - 1), 5, man_bits, bias=18) + rhs = apyfloat(0, 0, 3 << (man_bits - 3), 5, man_bits, bias=16) + expected = apyfloat(0, 1, 1 << (man_bits - 1), 5, man_bits, bias=17) + + assert (lhs + rhs).is_identical(expected) + assert (rhs + lhs).is_identical(expected) @pytest.mark.float_add diff --git a/lib/test/apyfloat/test_rounding.py b/lib/test/apyfloat/test_rounding.py index 152862298..f36dfb4fc 100644 --- a/lib/test/apyfloat/test_rounding.py +++ b/lib/test/apyfloat/test_rounding.py @@ -25,6 +25,51 @@ def test_issue_245(apyfloat: type[APyCFloat]): assert res.is_identical(APyFloat(0, 0, 0, 5, 2)) +@pytest.mark.float_add +@pytest.mark.parametrize( + ("man_bits", "zero_man_bits"), [(17, 17), (17, 9), (61, 61), (61, 17)] +) +@pytest.mark.parametrize("zero_bias", [15, 17]) +def test_add_zero_jam(man_bits: int, zero_man_bits: int, zero_bias: int): + one = APyFloat(0, 15, 0, 5, man_bits) + zero = APyFloat(0, 0, 0, 5, zero_man_bits, bias=zero_bias) + result_bias = (15 + zero_bias) // 2 + expected = APyFloat(0, result_bias, 1, 5, man_bits, bias=result_bias) + + with APyFloatQuantizationContext(QuantizationMode.JAM): + assert (one + zero).is_identical(expected) + assert (zero + one).is_identical(expected) + + +@pytest.mark.float_add +@pytest.mark.parametrize( + "quantization", + [ + QuantizationMode.JAM, + QuantizationMode.JAM_UNBIASED, + QuantizationMode.RND_CONV, + QuantizationMode.TRN, + QuantizationMode.TRN_INF, + QuantizationMode.TRN_AWAY, + ], +) +@pytest.mark.parametrize("sign", [0, 1]) +def test_add_negative_tentative_exponent(quantization: QuantizationMode, sign: int): + for apyfloat in (APyFloat, APyCFloat): + for man_bits in (17, 61): + rhs = apyfloat(0, 0, 0, 5, man_bits, bias=14) + expected = apyfloat(sign, 0, 0, 5, man_bits, bias=16) + if apyfloat is APyCFloat and quantization == QuantizationMode.JAM: + expected = apyfloat((sign, 0), (0, 0), (0, 1), 5, man_bits, bias=16) + + with APyFloatQuantizationContext(quantization): + for mantissa in (2, 3, 4, 6): + lhs = apyfloat(sign, 0, mantissa, 5, man_bits, bias=18) + + assert (lhs + rhs).is_identical(expected) + assert (rhs + lhs).is_identical(expected) + + @pytest.mark.float_add @pytest.mark.float_sub @pytest.mark.parametrize("man", [10, 60]) diff --git a/src/apyfloat_util.h b/src/apyfloat_util.h index 245714c47..0539fb209 100644 --- a/src/apyfloat_util.h +++ b/src/apyfloat_util.h @@ -1369,10 +1369,10 @@ template < = y_spec == dst_spec ? y : widening_man(y, y_spec.man_bits, dst_spec.man_bits); // Tentative exponent - exp_t x_true_exp = true_exp(x_wide, x_spec.bias); - exp_t new_exp = x_true_exp + dst_spec.bias; - if (new_exp > RES_MAX_EXP) { - exp_t exp = int(new_exp) < 0 ? 0 : RES_MAX_EXP; + const std::int64_t x_true_exp = true_exp(x_wide, x_spec.bias); + std::int64_t new_exp = x_true_exp + dst_spec.bias; + if (new_exp < 0 || new_exp > RES_MAX_EXP) { + exp_t exp = new_exp < 0 ? 0 : RES_MAX_EXP; man_t res_man = exp ? (qntz == QuantizationMode::JAM ? 1 : 0) : 0; z = { x_sign, exp, res_man }; return; @@ -1385,8 +1385,12 @@ template < // Align mantissa based on difference in exponent man_t my_aligned; - const unsigned exp_delta = x_true_exp - true_exp(y_wide, y_spec); - if (exp_delta <= 3) { + const std::int64_t exp_delta = x_true_exp - true_exp(y_wide, y_spec); + if (exp_delta < 0) { + // A subnormal y can have a higher exponent despite |y| <= |x|. + // Alignment gives my_aligned <= mx < CARRY_RES_LO. + my_aligned = my == 0 ? 0 : my << -exp_delta; + } else if (exp_delta <= 3) { my_aligned = my >> exp_delta; } else if (exp_delta >= _MAN_T_SIZE_BITS) { my_aligned = (my != 0); @@ -1418,8 +1422,9 @@ template < } new_man &= MAN_MASK; - qntz_func(new_man, new_exp, RES_MAX_EXP, 4, x_sign, FINAL_RES_LO, 7); - z = { x_sign, new_exp, new_man }; + exp_t res_exp = exp_t(new_exp); + qntz_func(new_man, res_exp, RES_MAX_EXP, 4, x_sign, FINAL_RES_LO, 7); + z = { x_sign, res_exp, new_man }; return; } @@ -1496,11 +1501,11 @@ template < const std::int64_t x_true_exp = true_exp(x_wide, x_spec.bias); const std::int64_t y_true_exp = true_exp(y_wide, y_spec.bias); - const std::uint64_t exp_delta = x_true_exp - y_true_exp; + const std::int64_t exp_delta = is_zero(y) ? 0 : x_true_exp - y_true_exp; - exp_t new_exp = x_true_exp + dst_spec.bias; - if (new_exp > RES_MAX_EXP) { - const exp_t exp = int(new_exp) < 0 ? 0 : RES_MAX_EXP; + std::int64_t new_exp = x_true_exp + dst_spec.bias; + if (new_exp < 0 || new_exp > RES_MAX_EXP) { + const exp_t exp = new_exp < 0 ? 0 : RES_MAX_EXP; const man_t res_man = exp ? (qntz == QuantizationMode::JAM ? 1 : 0) : 0; z = { x_sign, exp, res_man }; return; From d56d2105566acdfc7f0a7ff0adc87812b2f65a9d Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Fri, 30 Oct 2026 13:38:30 +0100 Subject: [PATCH 12/18] Fix in subnormal handling for addition --- CHANGELOG.md | 1 + lib/test/apyfloat/test_arithmetic.py | 125 ++++++++++++++++++++++++--- lib/test/apyfloat/test_rounding.py | 18 ++++ src/apyfloat_util.h | 12 ++- 4 files changed, 144 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3d63dcc2..eea5d4002 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Floating-point cast for values between the largest subnormal and the smallest normal value of the destination format. - Floating-point addition with mixed formats. +- Floating-point addition when subnormals are rounded to normals for large mantissas. ### Changed diff --git a/lib/test/apyfloat/test_arithmetic.py b/lib/test/apyfloat/test_arithmetic.py index 6768efe6c..b95a8071f 100644 --- a/lib/test/apyfloat/test_arithmetic.py +++ b/lib/test/apyfloat/test_arithmetic.py @@ -348,34 +348,50 @@ def test_sub_mixed_bias(apyfloat: type[APyCFloat]): ) +@pytest.mark.float_sub +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize("reverse_operands", [False, True]) +def test_sub_mixed_bias_subnormal_residual( + apyfloat: type[APyCFloat], reverse_operands: bool +): + lhs = apyfloat(0, 0, 1 << 58, 5, 61, bias=14) + rhs = apyfloat(0, 0, (1 << 60) - 2, 5, 61, bias=16) + if reverse_operands: + lhs, rhs = rhs, lhs + + expected = apyfloat(reverse_operands, 0, 1, 5, 61, bias=15) + assert (lhs - rhs).is_identical(expected) + + @pytest.mark.float_add @pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) -def test_add_mixed_bias_overflow(apyfloat: type[APyCFloat]): +@pytest.mark.parametrize("man_bits", [2, 61]) +def test_add_mixed_bias_overflow(apyfloat: type[APyCFloat], man_bits: int): """Test that a result can overflow to infinity due to a change in bias.""" - x = apyfloat(sign=0, exp=21, man=0, exp_bits=5, man_bits=2, bias=5) - y = apyfloat(sign=0, exp=0, man=0, exp_bits=5, man_bits=2, bias=25) + x = apyfloat(sign=0, exp=21, man=0, exp_bits=5, man_bits=man_bits, bias=5) + y = apyfloat(sign=0, exp=0, man=0, exp_bits=5, man_bits=man_bits, bias=25) # Add with zero assert (_ := x + y).is_identical( - apyfloat(sign=0, exp=31, man=0, exp_bits=5, man_bits=2, bias=15) + apyfloat(sign=0, exp=31, man=0, exp_bits=5, man_bits=man_bits, bias=15) ) # Add with zero but with larger bias difference - y = apyfloat(sign=0, exp=0, man=0, exp_bits=5, man_bits=2, bias=27) + y = apyfloat(sign=0, exp=0, man=0, exp_bits=5, man_bits=man_bits, bias=27) assert (_ := x + y).is_identical( - apyfloat(sign=0, exp=31, man=0, exp_bits=5, man_bits=2, bias=16) + apyfloat(sign=0, exp=31, man=0, exp_bits=5, man_bits=man_bits, bias=16) ) # Add with small normal number - y = apyfloat(sign=0, exp=1, man=1, exp_bits=5, man_bits=2, bias=28) + y = apyfloat(sign=0, exp=1, man=1, exp_bits=5, man_bits=man_bits, bias=28) assert (_ := x + y).is_identical( - apyfloat(sign=0, exp=31, man=0, exp_bits=5, man_bits=2, bias=16) + apyfloat(sign=0, exp=31, man=0, exp_bits=5, man_bits=man_bits, bias=16) ) # Add with subnormal number - y = apyfloat(sign=0, exp=0, man=1, exp_bits=5, man_bits=2, bias=28) + y = apyfloat(sign=0, exp=0, man=1, exp_bits=5, man_bits=man_bits, bias=28) assert (_ := x + y).is_identical( - apyfloat(sign=0, exp=31, man=0, exp_bits=5, man_bits=2, bias=16) + apyfloat(sign=0, exp=31, man=0, exp_bits=5, man_bits=man_bits, bias=16) ) @@ -492,6 +508,95 @@ def test_long_add(apyfloat: type[APyCFloat]): assert res.is_identical(apyfloat(0, 0, 0, 11, 60)) +@pytest.mark.float_add +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize("man", [0, 1 << 60]) +def test_add_61_bit_hidden_carry(apyfloat: type[APyCFloat], man: int): + value = apyfloat(0, 15, man, 5, 61) + expected = apyfloat(0, 16, man, 5, 61) + + assert (value + value).is_identical(expected) + + +@pytest.mark.float_sub +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize( + ("lhs_exp", "lhs_man", "rhs_exp", "rhs_man", "expected_exp", "expected_man"), + [ + (16, 0, 15, (1 << 61) - 1, 0, 1 << 14), + (1, 1, 0, 1, 1, 0), + (1, 1, 1, 0, 0, 1), + ], +) +def test_sub_long_normalization( + apyfloat: type[APyCFloat], + lhs_exp: int, + lhs_man: int, + rhs_exp: int, + rhs_man: int, + expected_exp: int, + expected_man: int, +): + lhs = apyfloat(0, lhs_exp, lhs_man, 5, 61) + rhs = apyfloat(0, rhs_exp, rhs_man, 5, 61) + expected = apyfloat(0, expected_exp, expected_man, 5, 61) + + assert (lhs - rhs).is_identical(expected) + + +@pytest.mark.float_add +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +def test_add_general_zero_exponent_scaling(apyfloat: type[APyCFloat]): + value = apyfloat(0, 1, 0, 5, 61, bias=16) + zero = apyfloat(0, 0, 0, 5, 61, bias=14) + expected = apyfloat(0, 0, 1 << 60, 5, 61, bias=15) + + assert (value + zero).is_identical(expected) + + +@pytest.mark.float_add +@pytest.mark.float_sub +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize("operation", ["add", "sub"]) +@pytest.mark.parametrize("exp_gap", [63, 64, 65]) +def test_add_subtract_sticky_alignment_boundaries( + apyfloat: type[APyCFloat], operation: str, exp_gap: int +): + lhs = apyfloat(0, 100, 0, exp_bits=8, man_bits=61) + rhs = apyfloat(0, 100 - exp_gap, 0, exp_bits=8, man_bits=61) + + result = lhs + rhs if operation == "add" else lhs - rhs + assert result.is_identical(lhs) + + +@pytest.mark.float_add +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize("reverse_operands", [False, True]) +@pytest.mark.parametrize( + ("lhs_man_bits", "rhs_sign", "rhs_man", "expected_man"), + [ + (61, 0, 1 << 60, 1 << 60), + (60, 0, 1 << 60, 1 << 60), + (60, 1, (1 << 60) - 2, 1), + ], +) +def test_add_subnormals_with_different_bias( + apyfloat: type[APyCFloat], + reverse_operands: bool, + lhs_man_bits: int, + rhs_sign: int, + rhs_man: int, + expected_man: int, +): + lhs = apyfloat(0, 0, 1 << (lhs_man_bits - 3), 5, lhs_man_bits, bias=14) + rhs = apyfloat(rhs_sign, 0, rhs_man, 5, 61, bias=16) + if reverse_operands: + lhs, rhs = rhs, lhs + + expected = apyfloat(0, 0, expected_man, 5, 61, bias=15) + assert (lhs + rhs).is_identical(expected) + + # Subtraction # Because subtraction is implemented as 'a+(-b)', the tests for addition will also cover # subtraction, but we still do some tests using the subtraction operator to make sure diff --git a/lib/test/apyfloat/test_rounding.py b/lib/test/apyfloat/test_rounding.py index f36dfb4fc..a3de19df4 100644 --- a/lib/test/apyfloat/test_rounding.py +++ b/lib/test/apyfloat/test_rounding.py @@ -41,6 +41,24 @@ def test_add_zero_jam(man_bits: int, zero_man_bits: int, zero_bias: int): assert (zero + one).is_identical(expected) +@pytest.mark.float_add +@pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) +@pytest.mark.parametrize("man_bits", [17, 61]) +@pytest.mark.parametrize( + "quantization", [QuantizationMode.TIES_EVEN, QuantizationMode.TO_POS] +) +def test_add_subnormal_rounding_to_normal( + apyfloat: type[APyCFloat], man_bits: int, quantization: QuantizationMode +): + value = apyfloat(0, 1, (1 << man_bits) - 1, 5, man_bits, bias=16) + zero = apyfloat(0, 0, 0, 5, man_bits, bias=14) + expected = apyfloat(0, 1, 0, 5, man_bits, bias=15) + + with APyFloatQuantizationContext(quantization): + assert (value + zero).is_identical(expected) + assert (zero + value).is_identical(expected) + + @pytest.mark.float_add @pytest.mark.parametrize( "quantization", diff --git a/src/apyfloat_util.h b/src/apyfloat_util.h index 0539fb209..b0008d4a4 100644 --- a/src/apyfloat_util.h +++ b/src/apyfloat_util.h @@ -1349,7 +1349,7 @@ template < return; } } else if (is_zero(x)) { - // If `x` is zero, than so is `y` + // If `x` is zero, then so is `y` bool res_sign = same_sign ? x_sign : qntz == QuantizationMode::TRN; man_t res_man = qntz == QuantizationMode::JAM ? 1 : 0; z = { res_sign, 0, res_man }; @@ -1405,7 +1405,7 @@ template < // Check for carry and cancellation if (new_man & CARRY_RES_LO) { new_exp++; - } else if (new_man & RES_LO) { + } else if (new_exp != 0 && (new_man & RES_LO)) { new_man <<= 1; } else { // Mantissa should be shifted @@ -1523,6 +1523,8 @@ template < if (apy_res.positive_greater_than_equal_pow2(1)) { new_exp++; apy_res >>= 1; + } else if (new_exp == 0) { + apy_res >>= 1; } else { // Check for cancellation by counting the number of left shifts needed // to make fx>=1.0 @@ -1563,6 +1565,12 @@ template < // Remove leading one if (apy_res.positive_greater_than_equal_pow2(0)) { + // Check if subnormal is promoted to normal + if (new_exp == 0) { + new_exp = 1; + // apy_res is not shifted since the exponent have the same scale: + // normal: 1-b, subnormal: 1-b. + } apy_res = apy_res - FX_ONE; } From e1760159a4821378ec21c61b0e81ce8b74da0ec3 Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Fri, 30 Oct 2026 15:47:19 +0100 Subject: [PATCH 13/18] Overhandling for FP addition with JAM --- CHANGELOG.md | 1 + lib/test/apyfloat/test_rounding.py | 21 +++++++++++++++++---- src/apyfloat_util.h | 20 ++++++++++++-------- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eea5d4002..39eab8933 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 the smallest normal value of the destination format. - Floating-point addition with mixed formats. - Floating-point addition when subnormals are rounded to normals for large mantissas. +- Overflow handling for floating-point addition with Jamming. ### Changed diff --git a/lib/test/apyfloat/test_rounding.py b/lib/test/apyfloat/test_rounding.py index a3de19df4..67942fab3 100644 --- a/lib/test/apyfloat/test_rounding.py +++ b/lib/test/apyfloat/test_rounding.py @@ -41,6 +41,18 @@ def test_add_zero_jam(man_bits: int, zero_man_bits: int, zero_bias: int): assert (zero + one).is_identical(expected) +@pytest.mark.float_add +@pytest.mark.parametrize("man_bits", [2, 61]) +def test_add_mixed_bias_overflow_jam(man_bits: int): + lhs = APyFloat(0, 21, 0, 5, man_bits, bias=5) + rhs = APyFloat(0, 0, 1, 5, man_bits, bias=27) + infinity = APyFloat(0, 31, 0, 5, man_bits, bias=16) + with APyFloatQuantizationContext(QuantizationMode.JAM): + res = lhs + rhs + print(res) + assert res.is_identical(infinity) + + @pytest.mark.float_add @pytest.mark.parametrize("apyfloat", [APyFloat, APyCFloat]) @pytest.mark.parametrize("man_bits", [17, 61]) @@ -76,14 +88,15 @@ def test_add_negative_tentative_exponent(quantization: QuantizationMode, sign: i for apyfloat in (APyFloat, APyCFloat): for man_bits in (17, 61): rhs = apyfloat(0, 0, 0, 5, man_bits, bias=14) - expected = apyfloat(sign, 0, 0, 5, man_bits, bias=16) - if apyfloat is APyCFloat and quantization == QuantizationMode.JAM: - expected = apyfloat((sign, 0), (0, 0), (0, 1), 5, man_bits, bias=16) + lsb = 1 if quantization == QuantizationMode.JAM else 0 + expected = apyfloat(sign, 0, lsb, 5, man_bits, bias=16) + if apyfloat is APyCFloat: + expected = apyfloat((sign, 0), (0, 0), (lsb, lsb), 5, man_bits, bias=16) with APyFloatQuantizationContext(quantization): for mantissa in (2, 3, 4, 6): lhs = apyfloat(sign, 0, mantissa, 5, man_bits, bias=18) - + print(lhs + rhs) assert (lhs + rhs).is_identical(expected) assert (rhs + lhs).is_identical(expected) diff --git a/src/apyfloat_util.h b/src/apyfloat_util.h index b0008d4a4..db22541fe 100644 --- a/src/apyfloat_util.h +++ b/src/apyfloat_util.h @@ -1371,10 +1371,12 @@ template < // Tentative exponent const std::int64_t x_true_exp = true_exp(x_wide, x_spec.bias); std::int64_t new_exp = x_true_exp + dst_spec.bias; - if (new_exp < 0 || new_exp > RES_MAX_EXP) { - exp_t exp = new_exp < 0 ? 0 : RES_MAX_EXP; - man_t res_man = exp ? (qntz == QuantizationMode::JAM ? 1 : 0) : 0; - z = { x_sign, exp, res_man }; + if (new_exp < 0) { + man_t res_man = (qntz == QuantizationMode::JAM) ? 1 : 0; + z = { x_sign, 0, res_man }; + return; + } else if (new_exp > RES_MAX_EXP) { + z = { x_sign, RES_MAX_EXP, 0 }; return; } @@ -1504,10 +1506,12 @@ template < const std::int64_t exp_delta = is_zero(y) ? 0 : x_true_exp - y_true_exp; std::int64_t new_exp = x_true_exp + dst_spec.bias; - if (new_exp < 0 || new_exp > RES_MAX_EXP) { - const exp_t exp = new_exp < 0 ? 0 : RES_MAX_EXP; - const man_t res_man = exp ? (qntz == QuantizationMode::JAM ? 1 : 0) : 0; - z = { x_sign, exp, res_man }; + if (new_exp < 0) { + man_t res_man = (qntz == QuantizationMode::JAM) ? 1 : 0; + z = { x_sign, 0, res_man }; + return; + } else if (new_exp > RES_MAX_EXP) { + z = { x_sign, RES_MAX_EXP, 0 }; return; } From 69c71a6dfb9e25b32930257fb258f83430df68ad Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Mon, 2 Nov 2026 09:39:29 +0100 Subject: [PATCH 14/18] Improve test coverage --- lib/test/apyfloat/test_rounding.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/lib/test/apyfloat/test_rounding.py b/lib/test/apyfloat/test_rounding.py index 67942fab3..bc28ff1f0 100644 --- a/lib/test/apyfloat/test_rounding.py +++ b/lib/test/apyfloat/test_rounding.py @@ -41,6 +41,34 @@ def test_add_zero_jam(man_bits: int, zero_man_bits: int, zero_bias: int): assert (zero + one).is_identical(expected) +@pytest.mark.float_add +@pytest.mark.float_sub +@pytest.mark.parametrize("man_bits", [17, 61]) +@pytest.mark.parametrize( + ("quantization", "expected_sign", "expected_mantissa"), + [ + (QuantizationMode.JAM, 0, 1), + (QuantizationMode.TIES_EVEN, 0, 0), + (QuantizationMode.TO_NEG, 1, 0), + ], +) +def test_add_sub_mixed_bias_cancellation( + man_bits: int, + quantization: QuantizationMode, + expected_sign: int, + expected_mantissa: int, +): + lhs = APyFloat(0, 15, 0, 5, man_bits, bias=15) + rhs = APyFloat(1, 17, 0, 5, man_bits, bias=17) + expected = APyFloat(expected_sign, 0, expected_mantissa, 5, man_bits, bias=16) + + with APyFloatQuantizationContext(quantization): + assert (lhs + rhs).is_identical(expected) + assert (rhs + lhs).is_identical(expected) + assert (lhs - (-rhs)).is_identical(expected) + assert (rhs - (-lhs)).is_identical(expected) + + @pytest.mark.float_add @pytest.mark.parametrize("man_bits", [2, 61]) def test_add_mixed_bias_overflow_jam(man_bits: int): From 0101f01f84c89f7a2144c460f108fc720fd6e14e Mon Sep 17 00:00:00 2001 From: Theodor Lindberg Date: Mon, 2 Nov 2026 22:18:22 +0100 Subject: [PATCH 15/18] Fix apy.from_bits for APyCFloat --- lib/apytypes/_utils.py | 43 +++++++++++++++++++++++++++++++++++++++++- lib/test/test_utils.py | 39 ++++++++++++++++++++++++++++++++------ 2 files changed, 75 insertions(+), 7 deletions(-) diff --git a/lib/apytypes/_utils.py b/lib/apytypes/_utils.py index 29b67a776..383d37aa6 100644 --- a/lib/apytypes/_utils.py +++ b/lib/apytypes/_utils.py @@ -517,6 +517,14 @@ def from_bits( ) -> APyCFloat: ... +@overload +def from_bits( + bit_patterns: tuple[Any, ...], + *, + spec: APyCFloat | APyCFloatArray, +) -> APyCFloat: ... + + @overload def from_bits( bit_patterns: Iterable[Any], @@ -659,6 +667,34 @@ def from_bits( ) -> APyFloat | APyCFloat: ... +@overload +def from_bits( + bit_patterns: tuple[Any, ...], + *, + int_bits: None = None, + frac_bits: None = None, + bits: None = None, + exp_bits: int, + man_bits: int, + bias: int | None = None, + force_complex: Literal[True], +) -> APyCFloat: ... + + +@overload +def from_bits( + bit_patterns: tuple[Any, ...], + *, + int_bits: None = None, + frac_bits: None = None, + bits: None = None, + exp_bits: int, + man_bits: int, + bias: int | None = None, + force_complex: bool, +) -> APyFloatArray | APyCFloat: ... + + @overload def from_bits( bit_patterns: Iterable[Any], @@ -784,10 +820,15 @@ def from_bits( actual_type = None if force_complex: actual_type = ( - APyCFloatArray if isinstance(bit_patterns, Iterable) else APyCFloat + APyCFloat + if isinstance(bit_patterns, tuple) + or not isinstance(bit_patterns, Iterable) + else APyCFloatArray ) else: actual_type = ( APyFloatArray if isinstance(bit_patterns, Iterable) else APyFloat ) + if actual_type is APyCFloat and not isinstance(bit_patterns, tuple): + bit_patterns = (bit_patterns,) return actual_type.from_bits(bit_patterns, exp_bits, man_bits, bias) diff --git a/lib/test/test_utils.py b/lib/test/test_utils.py index 1320da980..fdd8b0e0a 100644 --- a/lib/test/test_utils.py +++ b/lib/test/test_utils.py @@ -279,6 +279,30 @@ def test_from_bits(): APyFloatArray.from_bits([60, 61, 80, 82], exp_bits=5, man_bits=2) ) + assert from_bits(13, exp_bits=5, man_bits=3, force_complex=True).is_identical( + APyCFloat.from_bits((13, 0), exp_bits=5, man_bits=3) + ) + assert from_bits( + 13, exp_bits=5, man_bits=3, bias=6, force_complex=True + ).is_identical(APyCFloat.from_bits((13, 0), exp_bits=5, man_bits=3, bias=6)) + + for bit_patterns in ((13,), (13, 42)): + assert from_bits( + bit_patterns, exp_bits=5, man_bits=3, bias=6, force_complex=True + ).is_identical(APyCFloat.from_bits(bit_patterns, 5, 3, 6)) + + for bit_patterns, message in ( + ((), "tuple initializer with zero elements"), + ((1.5,), "tuple initializer with non-integer element"), + ((1, 2.5), "tuple initializer with non-integer element"), + ((1, 2, 3), "tuple initializer with more than two elements"), + ): + with pytest.raises(ValueError, match=message) as expected: + APyCFloat.from_bits(bit_patterns, 5, 3) + with pytest.raises(ValueError, match=message) as actual: + from_bits(bit_patterns, exp_bits=5, man_bits=3, force_complex=True) + assert str(actual.value) == str(expected.value) + assert from_bits([1, 2], int_bits=10, frac_bits=0, force_complex=True).is_identical( APyCFixedArray.from_bits([1, 2], int_bits=10, frac_bits=0) ) @@ -295,8 +319,8 @@ def test_from_bits_spec(): cfixed_array_spec = APyCFixedArray.from_complex([0], int_bits=5, frac_bits=2) float_spec = APyFloat.from_float(0, exp_bits=5, man_bits=3) float_array_spec = APyFloatArray.from_float([0], exp_bits=5, man_bits=3) - cfloat_spec = APyCFloat.from_complex(0, exp_bits=5, man_bits=3) - cfloat_array_spec = APyCFloatArray.from_complex([0], exp_bits=5, man_bits=3) + cfloat_spec = APyCFloat.from_complex(0, exp_bits=5, man_bits=3, bias=6) + cfloat_array_spec = APyCFloatArray.from_complex([0], exp_bits=5, man_bits=3, bias=6) for spec in (fixed_spec, fixed_array_spec): assert from_bits(13, spec=spec).is_identical( @@ -323,11 +347,14 @@ def test_from_bits_spec(): ) for spec in (cfloat_spec, cfloat_array_spec): - # Scalar case is omitted: from_bits() can't produce a scalar APyCFloat from a - # plain int, since APyCFloat.from_bits() requires a (real_bits, imag_bits) - # tuple. This is a pre-existing bug unrelated to `spec`. + assert from_bits(13, spec=spec).is_identical( + APyCFloat.from_bits((13, 0), exp_bits=5, man_bits=3, bias=6) + ) + assert from_bits((13, 42), spec=spec).is_identical( + APyCFloat.from_bits((13, 42), exp_bits=5, man_bits=3, bias=6) + ) assert from_bits([60, 61], spec=spec).is_identical( - APyCFloatArray.from_bits([60, 61], exp_bits=5, man_bits=3) + APyCFloatArray.from_bits([60, 61], exp_bits=5, man_bits=3, bias=6) ) with pytest.raises(ValueError, match="spec cannot be used with other specifiers"): From 5205b1bd35055e291a23d5ec98d8b3b36efff41c Mon Sep 17 00:00:00 2001 From: Simon Bjurek Date: Wed, 4 Nov 2026 10:33:44 +0100 Subject: [PATCH 16/18] Fix casing in docs and section on how to build documentation --- docs/comparison.rst | 4 ++-- docs/development.rst | 15 +++++++++++++++ docs/playground.rst | 2 +- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/docs/comparison.rst b/docs/comparison.rst index 33a5f1de7..e213a7582 100644 --- a/docs/comparison.rst +++ b/docs/comparison.rst @@ -187,7 +187,7 @@ Comparison matrix .. [#mpmathfootnote] ``mpmath`` can use ``gmpy`` as a backend to do faster arithmetic, but uses Python integers by default. -Performance Comparison +Performance comparison ---------------------- This benchmark compares relevant fixed-point libraries from the list above. @@ -199,7 +199,7 @@ It is updated every documentation build and may vary over time as the code is fu .. image:: _static/comparison_relative.png :alt: Benchmark relative to APyTypes for different fixed-point libraries. -Feature Comparison +Feature comparison ------------------ .. image:: _static/comparison_matrix.png diff --git a/docs/development.rst b/docs/development.rst index 3b88bdfae..9ea5167f9 100644 --- a/docs/development.rst +++ b/docs/development.rst @@ -102,3 +102,18 @@ You can then see example usage of the script by running python run_berkeley_cases.py -h These are intended to more long running tests. If any bugs or deviations are found, dedicated tests should be added to the regular test suite. + +Build the documentation +----------------------- + +First, Doxygen must be installed separately. + +Then, install the documentation dependencies and build the HTML documentation +from the repository root: + +.. code-block:: bash + + python -m pip install .[docs] + make -C docs html + +Open ``docs/_build/html/index.html`` in a browser to view the result. diff --git a/docs/playground.rst b/docs/playground.rst index 5a75b2eb4..b25bbf37a 100644 --- a/docs/playground.rst +++ b/docs/playground.rst @@ -1,7 +1,7 @@ APyTypes Playground =================== -Welcomde to APyTypes Playground! This is an interactive console with Python and APyTypes +Welcome to APyTypes Playground! This is an interactive console with Python and APyTypes in the web browser based on the `Pyodide `_ v0.28.2 terminal emulator 🐍. From 23b5ef998fbba94df999c560b629904c751e7cb8 Mon Sep 17 00:00:00 2001 From: Lia Date: Wed, 4 Nov 2026 19:07:49 +0100 Subject: [PATCH 17/18] Measure Windows C++ coverage with covdbg --- .covdbg.yaml | 15 +++++++++ .github/workflows/run_coverage.yml | 53 +++++++++++------------------- 2 files changed, 35 insertions(+), 33 deletions(-) create mode 100644 .covdbg.yaml diff --git a/.covdbg.yaml b/.covdbg.yaml new file mode 100644 index 000000000..b2731cded --- /dev/null +++ b/.covdbg.yaml @@ -0,0 +1,15 @@ +# Windows C++ coverage for run_coverage.yml (windows_msvc): the extension module +# (*_apytypes*.pyd), with the sources in this checkout, the same selection as before. +version: 1 +source_root: "." +coverage: + default: + files: + include: + - "src/**" + - "lib/**" + - "subprojects/**" + - "build/**" + modules: + include: + - "*_apytypes*.pyd" diff --git a/.github/workflows/run_coverage.yml b/.github/workflows/run_coverage.yml index fcb08bae5..5dbaafa55 100644 --- a/.github/workflows/run_coverage.yml +++ b/.github/workflows/run_coverage.yml @@ -129,6 +129,9 @@ jobs: os: ["windows-latest"] runs-on: ${{ matrix.os }} + permissions: + contents: read + id-token: write # covdbg identifies this repository by the job's OIDC token steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -145,48 +148,32 @@ jobs: run: | python -m pip install --upgrade pip python -m pip install pytest-cov ninja "meson>=1.10.1" meson-python numpy setuptools_scm - choco install opencppcoverage --no-progress -y - name: Install APyTypes shell: pwsh run: | git fetch --tags python -m pip install --no-deps --no-build-isolation -v --editable . -Csetup-args=-Dbuildtype=release -Csetup-args=-Ddebug=true -Csetup-args=-Db_lto=false -Csetup-args=-Doptimization=1 + # GitHub issues no OIDC token to pull requests from forks, so C++ coverage is measured on + # pushes and on pull requests from branches of this repository; fork pull requests run the tests only. + - name: Set up covdbg + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + uses: liasoft/setup-covdbg@08409fcb6447e0a1473b61701443fc2453c87380 # v1.1.1 + with: + version: 'latest' - name: Test with pytest and collect C++ coverage + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository shell: pwsh run: | - $openCppCoverage = $null - $cmd = Get-Command OpenCppCoverage -ErrorAction SilentlyContinue - if ($cmd) { - $openCppCoverage = $cmd.Source - } - if (-not $openCppCoverage) { - $chocoRoot = if ($env:ChocolateyInstall) { $env:ChocolateyInstall } else { 'C:\\ProgramData\\chocolatey' } - $candidates = @( - (Join-Path $chocoRoot 'bin\\OpenCppCoverage.exe'), - (Join-Path $chocoRoot 'lib\\opencppcoverage\\tools\\OpenCppCoverage.exe'), - (Join-Path $chocoRoot 'lib\\OpenCppCoverage\\tools\\OpenCppCoverage.exe'), - (Join-Path ${env:ProgramFiles} 'OpenCppCoverage\\OpenCppCoverage.exe'), - (Join-Path ${env:ProgramFiles(x86)} 'OpenCppCoverage\\OpenCppCoverage.exe') - ) - foreach ($candidate in $candidates) { - if ($candidate -and (Test-Path $candidate)) { - $openCppCoverage = $candidate - break - } - } - } - if (-not $openCppCoverage) { - throw 'OpenCppCoverage executable not found in expected Chocolatey/Program Files locations.' - } - & $openCppCoverage --quiet --cover_children --sources "${{ github.workspace }}" --modules "*_apytypes*.pyd" --export_type cobertura:coverage-windows-msvc.xml -- python -m pytest lib/test --log-level=DEBUG --color=yes - if (!(Test-Path 'coverage-windows-msvc.xml')) { - throw 'OpenCppCoverage did not produce coverage-windows-msvc.xml' - } - if ((Get-Item 'coverage-windows-msvc.xml').Length -lt 200) { - throw 'coverage-windows-msvc.xml was generated but appears empty' - } + covdbg --config .covdbg.yaml --follow-children --propagate-exit-code --output coverage-windows-msvc.covdb python -m pytest lib/test --log-level=DEBUG --color=yes + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + covdbg convert --input coverage-windows-msvc.covdb --format COBERTURA --output coverage-windows-msvc.xml + - name: Test with pytest + if: ${{ !(github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} + shell: pwsh + run: | + python -m pytest lib/test --log-level=DEBUG --color=yes - name: Upload coverage reports to Codecov - if: ${{ !cancelled()}} + if: ${{ !cancelled() && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: files: coverage-windows-msvc.xml From 102c9916461a589a242cbb87b2934170cc4fbb5e Mon Sep 17 00:00:00 2001 From: Lia Date: Wed, 4 Nov 2026 19:27:40 +0100 Subject: [PATCH 18/18] Let lcov accept gcov 15's inconsistent end lines on ubuntu-latest ubuntu-latest moved to Ubuntu 26.04 (gcov 15), where lcov stops on a mismatched end line for PyInit__apytypes in src/apytypes_wrapper.cc. lcov names --ignore-errors inconsistent as the bypass; linux_third_party has failed in Format coverage data on main since 2026-10-30. --- .github/workflows/run_coverage.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/run_coverage.yml b/.github/workflows/run_coverage.yml index 5dbaafa55..c4692ebcc 100644 --- a/.github/workflows/run_coverage.yml +++ b/.github/workflows/run_coverage.yml @@ -102,14 +102,14 @@ jobs: if: ${{ !cancelled()}} run: | lcov --rc branch_coverage=1 --rc geninfo_unexecuted_blocks=1 \ - --ignore-errors mismatch,mismatch --ignore-errors unused \ + --ignore-errors mismatch,mismatch,inconsistent --ignore-errors unused \ --ignore-errors mismatch --capture --directory . \ --output-file coverage.info lcov --rc branch_coverage=1 --rc geninfo_unexecuted_blocks=1 \ - --ignore-errors mismatch,mismatch --ignore-errors unused \ + --ignore-errors mismatch,mismatch,inconsistent --ignore-errors unused \ --ignore-errors mismatch --extract coverage.info $PWD/src/'*' lcov --rc branch_coverage=1 --rc geninfo_unexecuted_blocks=1 \ - --ignore-errors mismatch,mismatch --ignore-errors unused \ + --ignore-errors mismatch,mismatch,inconsistent --ignore-errors unused \ --ignore-errors mismatch --list coverage.info find . -name '*.gc*' -delete # gcovr --xml-pretty --exclude-unreachable-branches --print-summary -o cobertura.xml --root $PWD