The Numpy module has its own add, subtract, multiply, divide, mod, and remainder functions to perform arithmetic operations on a Numpy Array.
Lets look at an example of this first
Code Example 1
Fairly straight forward, create two numpy arrays and perform arithmetic operations
# Numpy Array Arithemetic Operations import numpy as np nparr1 = np.array([10, 20, 30, 40, 50]) nparr2 = np.array([6, 13, 5, 21, 9]) addarr = np.add(nparr1, nparr2) subarr = np.subtract(nparr1, nparr2) mularr = np.multiply(nparr1, nparr2) modarr = np.mod(nparr1, nparr2) remarr = np.remainder(nparr1, nparr2) divarr = np.divide(nparr1, nparr2) print("After arithmetic operations") print("Array Addition = ", addarr) print("Array Subtraction = ", subarr) print("Array Multiplication = ", mularr) print("Array Modulus = ", modarr) print("Array Remainder = ", remarr) print("Array division = ", divarr)
lets run this and you you should see the following output
>>> %Run numparrayarithmetic1.py After arithmetic operations Array Addition = [16 33 35 61 59] Array Subtraction = [ 4 7 25 19 41] Array Multiplication = [ 60 260 150 840 450] Array Modulus = [ 4 7 0 19 5] Array Remainder = [ 4 7 0 19 5] Array division = [1.66666667 1.53846154 6. 1.9047619 5.55555556]
Code Example 2
Now lets use built in python arithmetic operators
# Numpy Array Arithemetic Operations import numpy as np nparr1 = np.array([10, 20, 30, 40, 50]) nparr2 = np.array([6, 13, 5, 21, 9]) addarr = nparr1 + nparr2 subarr = nparr1 - nparr2 mularr = nparr1 * nparr2 modarr = nparr1 % nparr2 divarr = nparr1 / nparr2 print("After arithmetic operations") print("Array Addition = ", addarr) print("Array Subtraction = ", subarr) print("Array Multiplication = ", mularr) print("Array Modulus = ", modarr) print("Array division = ", divarr)
lets run this and you you should see the following output
>>> %Run numparrayarithmetic2.py After arithmetic operations Array Addition = [16 33 35 61 59] Array Subtraction = [ 4 7 25 19 41] Array Multiplication = [ 60 260 150 840 450] Array Modulus = [ 4 7 0 19 5] Array division = [1.66666667 1.53846154 6. 1.9047619 5.55555556]
Link
You can find these examples in the numpy section in our github repository
https://github.com/programmershelp/maxpython/tree/main/numpy
Files are called numparrayarithmetic1 and numparrayarithmetic2