NumPy true_divide()

The numpy.true_divide() function performs element-wise division of two arrays, ensuring a true division (floating-point division) regardless of the input data types.

Syntax

</>
Copy
numpy.true_divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)

Parameters

ParameterTypeDescription
x1array_likeDividend array.
x2array_likeDivisor array. Must be broadcastable to the shape of x1.
outndarray, None, or tuple of ndarray and None, optionalOptional output array where results are stored. If not provided, a new array is allocated.
wherearray_like, optionalBoolean mask specifying where to perform division. Where False, values remain unchanged.
castingstr, optionalControls how types are cast.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalDefines the data type of the output array.
subokbool, optionalDetermines whether to allow subclasses of ndarray.

Return Value

Returns an array with element-wise division results. If both x1 and x2 are scalars, a scalar is returned.


Examples

1. Basic Element-wise Division

Dividing two arrays element-wise using numpy.true_divide().

</>
Copy
import numpy as np

# Define two arrays
x1 = np.array([10, 20, 30, 40])
x2 = np.array([2, 4, 5, 8])

# Perform element-wise true division
result = np.true_divide(x1, x2)

# Print the result
print("Element-wise division:", result)

Output:

Element-wise division: [5.  5.  6.  5. ]

2. Broadcasting in Division

Dividing an array by a scalar, utilizing NumPy’s broadcasting.

</>
Copy
import numpy as np

# Define an array
x1 = np.array([10, 20, 30, 40])

# Define a scalar divisor
x2 = 10

# Perform element-wise true division
result = np.true_divide(x1, x2)

# Print the result
print("Array divided by scalar:", result)

Output:

Array divided by scalar: [1.  2.  3.  4. ]

3. Using the out Parameter

Storing the division result in a pre-allocated output array.

</>
Copy
import numpy as np

# Define two arrays
x1 = np.array([12, 18, 24, 36])
x2 = np.array([3, 6, 4, 9])

# Create an output array with the same shape
output_array = np.empty_like(x1, dtype=float)

# Perform true division and store result in output_array
np.true_divide(x1, x2, out=output_array)

# Print the output array
print("Stored result:", output_array)

Output:

Stored result: [4.  3.  6.  4. ]

4. Using the where Parameter

Performing division only for elements satisfying a condition.

</>
Copy
import numpy as np

# Define two arrays
x1 = np.array([12, 18, 24, 36])
x2 = np.array([3, 6, 4, 9])

# Define a condition (only perform division where x2 is greater than 5)
mask = x2 > 5

# Compute division where condition is True
result = np.true_divide(x1, x2, where=mask)

# Print the results
print("Division result with condition:", result)

Output:

Division result with condition: [0. 3. 0. 4.]

The division is performed only where the condition x2 > 5 is met. Other values remain unchanged.