numpy.around() in Python
The numpy.around() returns a new array with each element rounded to the given number of decimals. It is similar to numpy.round() function and supports various rounding options including rounding to integers or decimal places or even rounding to tens, hundreds and so forth.
import numpy as np
a = np.array([1.2, 2.5, 3.7, 4.4])
res = np.around(a)
print(res)
Output
[1. 2. 4. 4.]
np.around(a) rounds each element in the array to the nearest integer because the decimals parameter is not specified and defaults to 0. This means the function rounds all numbers to the nearest integer.
Syntax
numpy.around(a, decimals=0, out=None)
Parameters:
- a (array_like): Input array containing numeric values to be rounded.
- decimals (optional int, default=0): Number of decimal places to round to 0 rounds to nearest integer, positive values round to specified decimal places, negative values round left of the decimal like tens.
- out (ndarray, optional): Array to store the result and it must have the same shape as the output.
Returns: This function returns a rounded array with the same shape as the input.
Examples
Lets see some examples widely used:
1. Rounding to 2 decimal places
import numpy as np
a = np.array([1.2345, 2.6789, 3.14159])
res = np.around(a, decimals=2)
print(res)
Output
[1.23 2.68 3.14]
np.around(a, decimals=2) rounds each element in the array to 2 decimal places. The decimals=2 parameter tells the function to keep two digits after the decimal point for every number.
2. Rounding to the nearest ten (Negative decimals)
import numpy as np
a = np.array([123, 456, 789])
res = np.around(a, decimals=-1)
print(res)
Output
[120 460 790]
np.around(a, decimals=-1) rounds each element to the nearest ten. Negative decimals round to the left of the decimal point, so -1 rounds to the nearest multiple of 10.
3. Rounding to the nearest hundred
import numpy as np
a = np.array([123, 456, 789])
res = np.around(a, decimals=-2)
print(res)
Output
[100 500 800]
np.around(a, decimals=-2) rounds each element to the nearest hundred. Negative decimals round to the left of the decimal point, so -2 rounds to the nearest multiple of 100.
4. Using the out parameter to store result in pre-allocated array
import numpy as np
a = np.array([1.567, 2.345, 3.789])
out_array = np.empty_like(a)
np.around(a, decimals=1, out=out_array)
print(out_array)
Output
[1.6 2.3 3.8]
np.around(...) rounds each element to 1 decimal place and stores the result in out_array, avoiding the creation of a new array.