numpy icon indicating copy to clipboard operation
numpy copied to clipboard

BUG: np.positive ufunc and unary + operator fail on boolean arrays, while binary arithmetic works

Open qiqicliff opened this issue 4 months ago • 2 comments

Describe the issue:

The unary ufunc np.positive and the unary + operator raise a UFuncNoLoopError when applied to a boolean NumPy array. This is inconsistent with:

Python's built‑in semantics, where +True returns 1 and +False returns 0.

NumPy's binary arithmetic operations (e.g., np.add, + between arrays, np.multiply), which treat boolean values as integers (True → 1, False → 0) and work without error.

The positive ufunc is the identity operation – it should simply return the input unchanged (after casting to a numeric type). There is no mathematical reason to reject booleans, and the fact that binary operators accept them makes this omission surprising for users.

Reproduce the code example:

import numpy as np

b = np.array([True, False])

# Binary arithmetic works as expected:
print(np.add(b, 0))        # [1 0]
print(b + 0)               # [1 0]
print(np.multiply(b, 1))   # [1 0]

# These fail with the same error:
try:
    print(np.positive(b))
except TypeError as e:
    print("np.positive:", e)

try:
    print(+b)
except TypeError as e:
    print("unary +:", e)

Error message:

[1 0]
[1 0]
[1 0]
np.positive: ufunc 'positive' did not contain a loop with signature matching types <class 'numpy.dtypes.BoolDType'> -> None
unary +: ufunc 'positive' did not contain a loop with signature matching types <class 'numpy.dtypes.BoolDType'> -> None

Python and NumPy Versions:

Numpy 1.26.4 Python 3.8

Runtime Environment:

No response

How does this issue affect you or how did you find it:

No response

qiqicliff avatar Jul 25 '26 02:07 qiqicliff

There is no mathematical reason to reject booleans, and the fact that binary operators accept them makes this omission surprising for users.

And there’s no principled reason on our end either. Someone just needs to wire the ufunc loop up.

ngoldbaum avatar Jul 25 '26 19:07 ngoldbaum

I reproduced this on current main. I’d like to work on it. My plan is to register a bool loop for positive by reusing the existing BOOL_absolute implementation through cfunc_alias='absolute' and the logical-loop dispatch, rather than introducing another kernel. I’ll also update the existing bool tests with scalar and array coverage that verifies values and the bool result dtype.

dk3yyyy avatar Jul 29 '26 21:07 dk3yyyy