DEV Community

Cover image for Element-Wise Numerical Operations in NumPy: A Practical Guide with Examples
Lohith
Lohith

Posted on

Element-Wise Numerical Operations in NumPy: A Practical Guide with Examples

Numeric operations in NumPy are element-wise operations performed on NumPy arrays. These operations include basic arithmetic like addition, subtraction, multiplication, and division, as well as more complex operations like exponentiation, modulus and reciprocal. Here are some examples of these operations:

Addition:
You can add two arrays element-wise using the + operator or the np.add() function.

import numpy as np

# Define two arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Element-wise addition
result = np.add(a, b)  # or a + b
print(result)  

# Output: [5 7 9]
Enter fullscreen mode Exit fullscreen mode

Subtraction:
Similarly, subtraction is done using the - operator or np.subtract() function.

# Element-wise subtraction
result = np.subtract(a, b)  # or a - b
print(result)  

# Output: [-3 -3 -3]
Enter fullscreen mode Exit fullscreen mode

Multiplication:
For element-wise multiplication, use the * operator or np.multiply().

# Element-wise multiplication
result = np.multiply(a, b)  # or a * b
print(result)  

# Output: [ 4 10 18]
Enter fullscreen mode Exit fullscreen mode

Division:
Element-wise division can be performed with the / operator or np.divide().

# Element-wise division
result = np.divide(a, b)  # or a / b
print(result)  

# Output: [0.25 0.4  0.5 ]
Enter fullscreen mode Exit fullscreen mode

Exponentiation:
Raise the elements of one array to the powers of another using ** or np.power().

# Element-wise exponentiation
result = np.power(a, 2)  # or a ** 2
print(result)  

# Output: [1 4 9]
Enter fullscreen mode Exit fullscreen mode

Modulus:
The modulus operation returns the remainder of division using % or np.mod().

# Element-wise modulus
result = np.mod(a, b)  # or a % b
print(result)  

# Output: [1 2 3]
Enter fullscreen mode Exit fullscreen mode

Reciprocal:
The reciprocal of an array is obtained by taking the inverse of each element. In NumPy, you can compute the reciprocal using the np.reciprocal() function or the 1 / array expression.

import numpy as np

# Define an array
a = np.array([1, 2, 3])

# Element-wise reciprocal
reciprocal_result = np.reciprocal(a)  # or 1 / a
print(reciprocal_result)  

# Output: [1.         0.5        0.33333333]
Enter fullscreen mode Exit fullscreen mode

The reciprocal of each element in the array a is computed as follows:

  • Reciprocal of 1: 1.0
  • Reciprocal of 2: 0.5
  • Reciprocal of 3: approximately 0.3333 (rounded to 4 decimal places)

These operations are highly optimized in NumPy and can be performed on arrays of any size, making them very efficient for numerical computations😊.

Top comments (0)