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]
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]
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]
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 ]
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]
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]
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]
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)