Open In App
Related Articles

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

Improve Article
Improve
Save Article
Save
Like Article
Like

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

The time complexity of applying true division on each array element using NumPy’s true_divide() function is also O(n), since we’re applying a single operation to each element in the array. In this case, since the size of the array is 5, the time complexity of this operation is O(5) = O(1).

The auxiliary space complexity of this code is O(n), since we’re creating a new array rslt with the same number of elements as the original array x. However, since the size of the array is fixed at 5, the space complexity of this code is O(5) = O(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. ]

Time complexity: O(n), where n is the length of the array x.

Auxiliary space: O(n), as a new array of size n is created to store the result of the element-wise division.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 13 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials