Let's see the array division in action:
divide()
function does truncated integer division and normal floating-point division:a = np.array([2, 6, 5]) b = np.array([1, 2, 3]) print("Divide", np.divide(a, b), np.divide(b, a))
The result of the divide()
function is shown as follows:
Divide [2 3 1] [0 0 0]
As you can see, truncation took place.
true_divide()
function comes closer to the mathematical definition of division. Integer division returns a floating-point result and no truncation occurs:print("True Divide", np.true_divide(a, b), np.true_divide(b, a))
The result of the true_divide()
function is as follows:
True Divide [ 2. 3. 1.66666667] [ 0.5 0.33333333 0.6 ]
floor_divide()
function always returns an integer result. It is equivalent to calling the floor()
function after calling the divide()
function. The floor()
function discards the decimal part of a floating-point number and returns an integer:print("Floor Divide", np.floor_divide(a, b), np.floor_divide(b, a)) c = 3.14 * b print("Floor Divide 2", np.floor_divide(c, b), np.floor_divide(b, c))
The floor_divide()
function call results in:
Floor Divide [2 3 1] [0 0 0] Floor Divide 2 [ 3. 3. 3.] [ 0. 0. 0.]
/
operator is equivalent to calling the divide()
function:from __future__ import division
However, if this line is found at the beginning of a Python program, the true_divide()
function is called instead. So, this code will appear as follows:
print("/ operator", a/b, b/a)
The result is shown as follows:
/ operator [ 2. 3. 1.66666667] [ 0.5 0.33333333 0.6 ]
//
operator is equivalent to calling the floor_divide()
function. For example, look at the following code snippet:print("// operator", a//b, b//a) print("// operator 2", c//b, b//c)
The //
operator result is shown as follows:
// operator [2 3 1] [0 0 0] // operator 2 [ 3. 3. 3.] [ 0. 0. 0.]
The divide()
function truncates the integer division and normal floating-point division. The true_divide()
function always returns a floating-point result without any truncation. The floor_divide()
function always returns an integer result; the result is the same that you will get by calling the divide()
and floor()
functions consecutively (see dividing.py
):
from __future__ import print_function from __future__ import division import numpy as np a = np.array([2, 6, 5]) b = np.array([1, 2, 3]) print("Divide", np.divide(a, b), np.divide(b, a)) print("True Divide", np.true_divide(a, b), np.true_divide(b, a)) print("Floor Divide", np.floor_divide(a, b), np.floor_divide(b, a)) c = 3.14 * b print("Floor Divide 2", np.floor_divide(c, b), np.floor_divide(b, c)) print("/ operator", a/b, b/a) print("// operator", a//b, b//a) print("// operator 2", c//b, b//c)