Rounding to nearest int with numpy.rint() not consistent for .5

后端 未结 7 1420
余生分开走
余生分开走 2020-12-20 11:37

numpy\'s round int doesn\'t seem to be consistent with how it deals with xxx.5

In [2]: np.rint(1.5)
Out[2]: 2.0

In [3]: np.rint(10.5)
Out[3]: 10.0
<         


        
7条回答
  •  长情又很酷
    2020-12-20 12:08

    The built-in round function seems to do what you want, although it only works on scalars:

    def correct_round(x):
        try:
            y = [ round(z) for z in x ]
        except:
            y = round(x)    
        return y
    

    and then to verify:

    print correct_round([-2.5,-1.5,-0.5,0.5,1.5,2.5])
    > [-3.0, -2.0, -1.0, 1.0, 2.0, 3.0]
    

提交回复
热议问题