Any advantage of using np.add(), np.divide(), etc. compared to +, /, etc.?

Viewed 50

Recently I came across some codes that look like this:

a = np.divide(np.subtract(b, c), np.add(d, e))

In which a, b, c, d, e are all np.ndarray. This code line looks harder-to-understand compared to

a = (b-c)/(d+e)

Is there any advantage of using np.add(), np.divide(), etc. compared to +, /, etc. ?

Thanks so much.

1 Answers

numpy.add docs says that

The + operator can be used as a shorthand for np.add on ndarrays.

Is there any advantage of using np.add(), np.divide(), etc. compared to +, /, etc. ?

np.add is first class citizien, so you might for example do

def myfunction(arr1, arr2, action):
    return action(arr1,arr2)

and used it like

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
total = myfunction(a,b,np.add)

rather than doing something like

def myfunction(arr1, arr2, action):
    if action=="+":
        return arr1 + arr2
    elif action=="/":
        return arr1 / arr2
    ...

Please also note that if arguments are not numpys array you might other result than using just +, e.g.

import numpy as np
a = [1,2,3]
b = [4,5,6]
print(a+b) # [1, 2, 3, 4, 5, 6]
print(np.add(a,b)) # [5 7 9]
Related