On Thu, Mar 16, 2023 at 7:57 PM Sergio Callegari <sergio.calleg...@gmail.com>
wrote:

> I am trying to use the `clip` method to transform floats to integers with
> clipping. I was expecting to be able to do both the clipping and the type
> conversion at once, passing the `dtype` parameter to `clip`, together with
> a suitable `casting` param. Such expectation came from reading the
> documentation of the `dtype` param for u-funcs that states that this
> parameter "Overrides the DType of the output arrays". Unfortunately, using
> the `dtype` parameter with `clip` causes the type conversion to be
> practiced before the clipping, not after it.  Is this how it is expected to
> operate?
>

Yes, that's how it is working. The docs (and design) are indeed confusing -
the `dtype` keyword doesn't quite do what you'd expect here. It selects the
internal loops for the specified dtype, rather than only changing the
output dtype. So you get this kind of weirdness:

>>> x = np.array([1, 5, 259], dtype=np.uint16)
>>> np.clip(x, 3, 200, dtype=np.uint8)
array([3, 5, 3], dtype=uint8)
>>> np.clip(x, 3, 200).astype(np.uint8)
array([  3,   5, 200], dtype=uint8)

I don't think the behavior can be changed. The docs already hint at what is
happening: "The exact calculation DTypes chosen may depend on the ufunc and
the inputs may be cast to this DType to perform the calculation."

Cheers,
Ralf
_______________________________________________
NumPy-Discussion mailing list -- numpy-discussion@python.org
To unsubscribe send an email to numpy-discussion-le...@python.org
https://mail.python.org/mailman3/lists/numpy-discussion.python.org/
Member address: arch...@mail-archive.com

Reply via email to