NumPy: Round up/down array elements (np.floor, np.trunc, np.ceil)
You can use np.floor()
, np.trunc()
, and np.ceil()
to round up and down the elements in a NumPy array (ndarray
).
Considering both positive and negative values, there are four main types of rounding: toward negative infinity, toward zero, toward positive infinity, and towards infinity.
You can use np.round()
to round half to even.
For rounding up and down decimals using the math
module, refer to the following article.
The NumPy version used in this article is as follows. Note that functionality may vary between versions.
import numpy as np
print(np.__version__)
# 1.26.1
Round down (= round toward negative infinity): np.floor()
Use np.floor()
to round toward negative infinity.
a = np.array([[10.0, 10.1, 10.9], [-10.0, -10.1, -10.9]])
print(a)
# [[ 10. 10.1 10.9]
# [-10. -10.1 -10.9]]
print(np.floor(a))
# [[ 10. 10. 10.]
# [-10. -11. -11.]]
print(np.floor(a).dtype)
# float64
The returned data type is a floating-point number (float
). Use astype()
to convert it to an integer (int
). This also applies to np.trunc()
, np.ceil()
, etc.
print(np.floor(a).astype(int))
# [[ 10 10 10]
# [-10 -11 -11]]
You can also specify a scalar value, which applies to np.trunc()
, np.ceil()
, etc.
print(np.floor(10.1))
# 10.0
Round toward zero (= truncate): np.trunc()
, np.fix()
, cast to int
Use np.trunc()
to round toward zero.
a = np.array([[10.0, 10.1, 10.9], [-10.0, -10.1, -10.9]])
print(a)
# [[ 10. 10.1 10.9]
# [-10. -10.1 -10.9]]
print(np.trunc(a))
# [[ 10. 10. 10.]
# [-10. -10. -10.]]
np.fix()
also rounds toward zero.
print(np.fix(a))
# [[ 10. 10. 10.]
# [-10. -10. -10.]]
Alternatively, casting a floating-point number (float
) to an integer (int
) using astype()
also rounds towards zero.
print(a.astype(int))
# [[ 10 10 10]
# [-10 -10 -10]]
Round up (= round toward positive infinity): np.ceil()
Use np.ceil()
to round toward positive infinity.
a = np.array([[10.0, 10.1, 10.9], [-10.0, -10.1, -10.9]])
print(a)
# [[ 10. 10.1 10.9]
# [-10. -10.1 -10.9]]
print(np.ceil(a))
# [[ 10. 11. 11.]
# [-10. -10. -10.]]
Round toward infinity
As of version 1.26
, NumPy has no function for rounding toward infinity, but it can be achieved as follows:
a = np.array([[10.0, 10.1, 10.9], [-10.0, -10.1, -10.9]])
print(a)
# [[ 10. 10.1 10.9]
# [-10. -10.1 -10.9]]
print(np.copysign(np.ceil(np.abs(a)), a))
# [[ 10. 11. 11.]
# [-10. -11. -11.]]
The absolute value is obtained using np.abs()
, then rounded up with np.ceil()
, and the original sign is restored with np.copysign()
.