2

I see that Universal Function(ufunc) is used for performing element wise array operations.

 arr = np.arange(5)
 arr2 = np.arange(5,10)
 np.add(arr,arr2)

This piece of code is similar to arr + arr2. In that case why should we use ufunc?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Meghana Bandaru
  • 67
  • 1
  • 2
  • 6

1 Answers1

2

Because it's a function which comes with a lot of features that a simple add expression won't provide you with. You can override the ufunc objects based on your expected behavior in certain situations and yet benefit from all its functionalities.

You can see that by just looking at the function's header:

numpy.add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Read more in doc:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html

And:

https://docs.scipy.org/doc/numpy/reference/ufuncs.html#ufuncs-kwargs\

Also note that whenever you do a + b if a or b is an ndarray, add(a, b) is called internally by numpy. So There's no difference when both arguments are ndarray.

Another good functionality that ufuncs provide is that you can perform numpy functionalities directly on python objects.

In [20]: np.add([2, 3, 4], 4)
Out[20]: array([6, 7, 8])

This is while if you do the sum in Python you'll get a TypeError:

In [21]: [2, 3, 4] + 4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-0a8f512c0d3a> in <module>()
----> 1 [2, 3, 4] + 4

TypeError: can only concatenate list (not "int") to list
Mazdak
  • 105,000
  • 18
  • 159
  • 188