NumPy ufunc Simple Arithmetic

NumPy's arithmetic ufuncs -- add, subtract, multiply, divide, power, and mod -- let you perform basic math across entire arrays at once, element by element.

The Core Arithmetic ufuncs

NumPy provides a dedicated ufunc for each basic arithmetic operator: np.add, np.subtract, np.multiply, np.divide, np.power, and np.mod (or np.remainder). Each one takes two array-like arguments of the same or broadcastable shapes and returns a new array containing the element-wise result.

Addition and Subtraction

np.add(a, b) is equivalent to a + b when a and b are NumPy arrays, and np.subtract(a, b) is equivalent to a - b. NumPy also overloads the standard Python operators for arrays, so both forms are common in real code -- the ufunc form is useful when you want to pass an out array or apply the operation through methods like np.add.reduce.

Example

import numpy as np

a = np.array([10, 20, 30, 40])
b = np.array([1, 2, 3, 4])

print(np.add(a, b))        # [11 22 33 44]
print(np.subtract(a, b))   # [ 9 18 27 36]
print(a + b)                # same result as np.add(a, b)

Multiplication, Division, Power, and Mod

np.multiply and np.divide perform element-wise multiplication and division. np.power(a, b) raises each element of a to the corresponding power in b, and np.mod(a, b) (aliased as np.remainder) returns the element-wise remainder of division. All four respect NumPy's broadcasting rules, so a single scalar can be combined with an entire array in one call.

Example

import numpy as np

a = np.array([10, 20, 30, 40])
b = np.array([3, 4, 5, 6])

print(np.multiply(a, b))   # [ 30  80 150 240]
print(np.divide(a, b))     # [3.333 5.    6.    6.667]
print(np.power(a, 2))      # [ 100  400  900 1600] -- broadcasting a scalar
print(np.mod(a, b))        # [1 0 0 4]
Note: np.divmod(a, b) returns both the quotient and the remainder in a single call, saving you from calling np.divide and np.mod separately.
  • Operator symbols (+, -, *, /, **, %) call these same ufuncs behind the scenes on NumPy arrays.
  • Division by zero produces inf, -inf, or nan rather than raising an exception, along with a RuntimeWarning.
  • All arithmetic ufuncs broadcast, so you can combine a full array with a single scalar or a smaller compatible array.
  • The out parameter lets you write results into a pre-allocated array, avoiding extra memory allocation in tight loops.
  • np.add.reduce(a) sums all elements of a, echoing how Python's built-in sum() works but at C speed.
Operatorufunc
+np.add
-np.subtract
*np.multiply
/np.divide
**np.power
%np.mod / np.remainder

Example

import numpy as np

prices = np.array([19.99, 5.49, 12.00, 3.25])
quantities = np.array([2, 5, 1, 8])

line_totals = np.multiply(prices, quantities)
print(line_totals)

order_total = np.add.reduce(line_totals)
print(f'Order total: {order_total:.2f}')

Exercise: NumPy ufunc Simple Arithmetic

What does np.add(arr1, arr2) do for two same-shaped arrays?