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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

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

Example 2: 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.