Numpy Math functions

Numpy

In this article, we will learn about basic NumPy math functions on array elements. We will learn with an example of how we can do addition, subtraction, multiplications, etc on NumPy arrays.

1. Addition

In this example, we will learn addition operation on NumPy array.We can Add a number to each array element as in example below:

In the output you can see each element got the addition of 1.

import numpy as np

arr = np.array([2,4,6,8])

# here adding 1 to each element
array_one = np.add(arr,1) 
print("After adding 1 to each element",array_one)

Output :

After adding 1 to each element [3 5 7 9]

2. Subtraction

We can Subtract a number from each array element

import numpy as np

arr = np.array([2,4,6,8])

array_two = np.subtract(arr,2) 

# here subtract 2 from each array element

print("After subtracting 2 from each element",array_two)

Output :

After subtracting 2 from each element [0 2 4 6]

3. Multiply of Numpy array element

We can Multiply a number to each array element


import numpy as np

arr = np.array([2,4,6,8])
array_three = np.multiply(arr,3) 

# here Multiply 3 to each array element

print("After multiply 3 to each element",array_three)

Output :

After multiply 3 to each element [ 6 12 18 24]

4. Power

We can do power to each element by using power function()

import numpy as np

arr = np.array([2,4,6,8])
array_four = np.power(arr,5) 

# here each array element to the 5th power

print("Doing power to 5 to each element",array_four)

Output :

Doing power to 5 to each element [ 32 1024 7776 32768]

5. Division

We can Divide each array element by a number. If we try division by 0 then it returns each element as inf

import numpy as np

arr = np.array([2,4,6,8])

# here Divide each array element by 4

array_five = np.divide(arr,4) 

print("After dividing by 4 to each element",array_five)

Output :

After dividing by 4 to each element [0.5 1. 1.5 2. ]

Dividing a NumPy array elements by zero

When you try this division then you may get a warning from the interpreter.

import numpy as np

arr = np.array([2,4,6,8])
array_six = np.divide(arr,0)
print("After dividing by 0 to each element",array_six)


Output :

RuntimeWarning: divide by zero encountered in true_divide
After dividing by 0 to each element [inf inf inf inf]