Skip to content

ENH: __trunc__ for floating and integer types #28949

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions doc/release/upcoming_changes/28949.new_function.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Add ``__trunc__`` method to NumPy scalar types
==============================================

NumPy scalar floating and integer types now implement the ``__trunc__`` special method, matching Python’s built-in numeric types. This enables direct use of :func:`math.trunc` and the ``__trunc__`` dunder method on NumPy scalars:

Examples
--------

.. code-block:: python

>>> import numpy as np
>>> import math
>>> math.trunc(np.float16(np.pi))
3
>>> np.float16(-np.pi).__trunc__()
-3
>>> np.int32(42).__trunc__()
42

Attempting to truncate infinite or NaN values for floating point types will now raise the same errors as Python floats.

.. versionadded:: 2.3
2 changes: 2 additions & 0 deletions numpy/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,8 @@ class _RoundMixin:
def __round__(self, /, ndigits: None = None) -> int: ...
@overload
def __round__(self, /, ndigits: SupportsIndex) -> Self: ...
@overload
def __trunc__(self, /) -> int: ...

@type_check_only
class _IntegralMixin(_RealMixin):
Expand Down
32 changes: 32 additions & 0 deletions numpy/_core/_add_newdocs_scalars.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,24 @@ def add_newdoc_for_scalar_type(obj, fixed_aliases, doc):
False
"""))

add_newdoc('numpy._core.numerictypes', float_name, ('__trunc__',
f"""
{float_name}.__trunc__() -> int

Return the floating point number with the fractional part removed,
leaving the integer part.

.. versionadded:: 2.3

Examples
--------
>>> np.{float_name}(np.pi).__trunc__()
3
>>> import math
>>> math.trunc(np.{float_name}(-np.pi))
-3
"""))

for int_name in ('int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32',
'int64', 'uint64', 'int64', 'uint64', 'int64', 'uint64'):
# Add negative examples for signed cases by checking typecode
Expand All @@ -387,3 +405,17 @@ def add_newdoc_for_scalar_type(obj, fixed_aliases, doc):
>>> np.{int_name}(-127).bit_count()
7
""" if dtype(int_name).char.islower() else "")))

add_newdoc('numpy._core.numerictypes', int_name, ('__trunc__',
f"""
{int_name}.__trunc__() -> int

Truncating an Integral returns itself.

.. versionadded:: 2.3

Examples
--------
>>> np.{int_name}(127).__trunc__()
127
"""))
6 changes: 6 additions & 0 deletions numpy/_core/src/multiarray/scalartypes.c.src
Original file line number Diff line number Diff line change
Expand Up @@ -2886,6 +2886,9 @@ static PyMethodDef @name@type_methods[] = {
{"is_integer",
(PyCFunction)@name@_is_integer,
METH_NOARGS, NULL},
{"__trunc__",
(PyCFunction)gentype_int,
METH_NOARGS, NULL},
/* for typing */
{"__class_getitem__",
(PyCFunction)numbertype_class_getitem,
Expand Down Expand Up @@ -2918,6 +2921,9 @@ static PyMethodDef @name@type_methods[] = {
{"bit_count",
(PyCFunction)npy_@name@_bit_count,
METH_NOARGS, NULL},
{"__trunc__",
(PyCFunction)gentype_int,
METH_NOARGS, NULL},
{NULL, NULL, 0, NULL} /* sentinel */
};
/**end repeat**/
Expand Down
31 changes: 31 additions & 0 deletions numpy/_core/tests/test_scalar_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Test the scalar constructors, which also do type-coercion
"""
import fractions
import math
import platform
import types
from typing import Any
Expand Down Expand Up @@ -133,6 +134,36 @@ def test_false(self, code: str) -> None:
continue
assert not value.is_integer()

class TestTruncate:
@pytest.mark.parametrize("code", np.typecodes["Float"])
@pytest.mark.parametrize("value", [0, -0, np.pi, -np.pi])
def test_basic_float(self, code, value):
dtype_value = np.dtype(code).type(value)
assert math.trunc(value) == math.trunc(dtype_value)

@pytest.mark.parametrize("code", np.typecodes["AllInteger"])
@pytest.mark.parametrize("limit", ["min", "max"])
def test_edgcases_integer(self, code, limit):
dtype = np.dtype(code).type
value = getattr(np.iinfo(dtype), limit)
assert math.trunc(dtype(value)) == math.trunc(int(value))

@pytest.mark.parametrize("code", np.typecodes["Float"])
@pytest.mark.parametrize("limit", ["min", "max"])
def test_edgcases_float(self, code, limit):
dtype = np.dtype(code).type
value = getattr(np.finfo(dtype), limit)
assert math.trunc(dtype(value)) == int(value)

@pytest.mark.parametrize("str_value, exception_class, match", [
("inf", OverflowError, "cannot convert (float|longdouble) infinity to integer"),
("-inf", OverflowError, "cannot convert (float|longdouble) infinity to integer"),
("nan", ValueError, "cannot convert (float|longdouble) NaN to integer"),
])
@pytest.mark.parametrize("code", np.typecodes["Float"])
def test_special_float(self, str_value, exception_class, match, code):
with pytest.raises(exception_class, match=match):
math.trunc(np.dtype(code).type(str_value))

class TestClassGetItem:
@pytest.mark.parametrize("cls", [
Expand Down
1 change: 0 additions & 1 deletion numpy/typing/tests/data/fail/scalars.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,4 @@ c8.__getnewargs__() # type: ignore[attr-defined]
f2.__getnewargs__() # type: ignore[attr-defined]
f2.hex() # type: ignore[attr-defined]
np.float16.fromhex("0x0.0p+0") # type: ignore[attr-defined]
f2.__trunc__() # type: ignore[attr-defined]
f2.__getformat__("float") # type: ignore[attr-defined]
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy