0

Should the keyword argument dtype is not considered in np.equal?

In the function documentation, it seems to indicate that dtype should a valid keyword argument, and I couldn't find anything saying that it will be ignored, but when using logical ufuncs, it does not seem to be used:

>>> import numpy as np
>>> np.__version__
'1.14.2'
>>> a = b = np.arange(2).astype(np.uint8)
>>> np.equal(a, b, dtype=float).dtype
dtype('bool')
>>> np.add(a, b).dtype
dtype('uint8')
>>> np.add(a, b, dtype=float).dtype
dtype('float64')

I would expect any ufunc to have the same output type if the return dtype is specified, but np.add behaves as I expected, while np.equal does not. Is this behavior intended?

cnapun
  • 93
  • 6

1 Answers1

2

np.equal() is a "ufunc", all of which have an optional dtype parameter. But not all ufuncs actually need the dtype parameter--it's just part of their universal signature.

It is very uncommon to want to change the output dtype of np.equal(), but if you must, you can do this:

result = np.empty(np.broadcast(a, b).shape, float)
np.equal(a, b, out=result)

The out parameter makes dtype irrelevant (for all ufuncs), and you end up with 0.0 and 1.0 values in result.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Is this behavior documented anywhere? In the ufunc documentation, under the keyword argument it says "Overrides the dtype of the calculation and output arrays. Similar to signature," which seems to indicate `dtype` should be used. – cnapun May 03 '18 at 03:05
  • 1
    @cnapun: The docs say *"Sometimes you may have an array of a certain data type and wish to add up all of its elements, but the result does not fit into the data type of the array."* - so the stated purpose of the `dtype` parameter is irrelevant for `equal()` because there is no way the result doesn't fit into `bool`. You can read between the lines to understand why `dtype` does nothing for `equal()`. Of course, if you strongly believe it should do something, you could submit a pull request for NumPy to enhance it. – John Zwinck May 03 '18 at 03:08
  • Ah I didn't see that. Thanks for pointing that out; it makes this make more sense. . – cnapun May 03 '18 at 03:13