How to round the elements of a float array in python ?

Published: March 22, 2019

DMCA.com Protection Status

To round the elements of a float array in python, a solution is to use the numpy function around, example:

>>> import numpy as np
>>> A = np.array((0.4,  1.6, 2.1, -0.7, 0.9))
>>> np.around(A)
array([ 0.,  2.,  2., -1.,  1.])

It is also possible to define the number of decimals:

 >>> A = np.array((0.04,  1.06, 2.1, -0.7, 0.09))
 >>> np.around(A, decimals=1)
 array([ 0. ,  1.1,  2.1, -0.7,  0.1])

Note: see also How to convert a float array to an integer array in python ?

References