numpy.round#
- numpy.round(a,decimals=0,out=None)[source]#
Evenly round to the given number of decimals.
- Parameters:
- aarray_like
Input data.
- decimalsint, optional
Number of decimal places to round to (default: 0). Ifdecimals is negative, it specifies the number of positions tothe left of the decimal point.
- outndarray, optional
Alternative output array in which to place the result. It must havethe same shape as the expected output, but the type of the outputvalues will be cast if necessary. SeeOutput type determinationfor more details.
- Returns:
- rounded_arrayndarray
An array of the same type asa, containing the rounded values.Unlessout was specified, a new array is created. A reference tothe result is returned.
The real and imaginary parts of complex numbers are roundedseparately. The result of rounding a float is a float.
Notes
For values exactly halfway between rounded decimal values, NumPyrounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,-0.5 and 0.5 round to 0.0, etc.
np.rounduses a fast but sometimes inexact algorithm to roundfloating-point datatypes. For positivedecimals it is equivalent tonp.true_divide(np.rint(a*10**decimals),10**decimals), which haserror due to the inexact representation of decimal fractions in the IEEEfloating point standard[1] and errors introduced when scaling by powersof ten. For instance, note the extra “1” in the following:>>>np.round(56294995342131.5,3)56294995342131.51
If your goal is to print such values with a fixed number of decimals, it ispreferable to use numpy’s float printing routines to limit the number ofprinted decimals:
>>>np.format_float_positional(56294995342131.5,precision=3)'56294995342131.5'
The float printing routines use an accurate but much more computationallydemanding algorithm to compute the number of digits after the decimalpoint.
Alternatively, Python’s builtin
roundfunction uses a more accuratebut slower algorithm for 64-bit floating point values:>>>round(56294995342131.5,3)56294995342131.5>>>np.round(16.055,2),round(16.055,2)# equals 16.0549999999999997(16.06, 16.05)
References
[1]“Lecture Notes on the Status of IEEE 754”, William Kahan,https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
Examples
>>>importnumpyasnp>>>np.round([0.37,1.64])array([0., 2.])>>>np.round([0.37,1.64],decimals=1)array([0.4, 1.6])>>>np.round([.5,1.5,2.5,3.5,4.5])# rounds to nearest even valuearray([0., 2., 2., 4., 4.])>>>np.round([1,2,3,11],decimals=1)# ndarray of ints is returnedarray([ 1, 2, 3, 11])>>>np.round([1,2,3,11],decimals=-1)array([ 0, 0, 0, 10])