Skip to content
Related Articles

Related Articles

How to get element-wise true division of an array using Numpy?

View Discussion
Improve Article
Save Article
  • Last Updated : 02 Sep, 2020
View Discussion
Improve Article
Save Article

True Division in Python3 returns a floating result containing the remainder of the division. To get the true division of an array, NumPy library has a function numpy.true_divide(x1, x2). This function gives us the value of true division done on the arrays passed in the function. To get the element-wise division we need to enter the first parameter as an array and the second parameter as a single element.

Syntax: np.true_divide(x1,x2) 
Parameters:

  • x1: The dividend array
  • x2: divisor (can be an array or an element)

Return: If inputs are scalar then scalar; otherwise array with arr1 / arr2(element- wise) i.e. true division

Now, let’s see an example:

Example 1: 

Python3




# import library
import numpy as np
  
# create 1d-array
x = np.arange(5)
  
print("Original array:"
      x)
  
# apply true division 
# on each array element
rslt = np.true_divide(x, 4)
  
print("After the element-wise division:"
      rslt)

Output :

Original array: [0 1 2 3 4]
After the element-wise division: [0.   0.25 0.5  0.75 1.  ]

Example 2: 

Python3




# import library
import numpy as np
  
# create a 1d-array
x = np.arange(10)
  
print("Original array:"
      x)
  
# apply true division 
# on each array element
rslt = np.true_divide(x, 3)
  
print("After the element-wise division:",
      rslt)

Output:

Original array: [0 1 2 3 4 5 6 7 8 9]
After the element-wise division: [0. 0.33333333 0.66666667 1. 1.33333333 1.66666667
2. 2.33333333 2.66666667 3. ]


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!