用python取整从img读取的numpy浮点数组,返回的值未取整

用python取整从img读取的numpy浮点数组,返回的值未取整,python,numpy,floating-point,Python,Numpy,Floating Point,由于某些原因,浮点numpy数组的简单舍入似乎不起作用 我通过读取一个巨大的img(形状为(73527472))得到numpy数组。Ex值: >>> imarray[3500:3503, 5000:5003] array([[ 73.33999634, 73.40000153, 73.45999908], [ 73.30999756, 73.37999725, 73.43000031], [ 73.30000305, 73.36000061

由于某些原因,浮点numpy数组的简单舍入似乎不起作用

我通过读取一个巨大的img(形状为(73527472))得到numpy数组。Ex值:

>>> imarray[3500:3503, 5000:5003]
array([[ 73.33999634,  73.40000153,  73.45999908],
       [ 73.30999756,  73.37999725,  73.43000031],
       [ 73.30000305,  73.36000061,  73.41000366]], dtype=float32)
对于舍入,我只是尝试对原始值使用numpy.around(),还将值写入一个新数组,一个原始数组的副本,但由于某些原因没有结果

arr=imarray
numpy.around(imarray, decimals=3, out=arr)
arr[3500,5000] #results in 73.3399963379, as well as accessing imarray
所以,更高的精度!!! 是因为这么大的阵列吗


我需要对其进行四舍五入以获得最频繁的值(模式),并且我正在搜索vay以避免越来越多的库。

您的数组具有dtype
float32
。这是一个4字节的浮点。 使用
float32
表示的最接近73.340的浮点值约为73.33999634:

In [62]: x = np.array([73.33999634, 73.340], dtype = np.float32)

In [63]: x
Out[63]: array([ 73.33999634,  73.33999634], dtype=float32)
因此我认为
np.around
是正确的四舍五入,只是您的
dtype
粒度太大,无法四舍五入到您可能期望的数字

In [60]: y = np.around(x, decimals = 3)

In [61]: y
Out[61]: array([ 73.33999634,  73.33999634], dtype=float32)
然而,如果数据类型为
np.float64

In [64]: x = np.array([73.33999634, 73.340], dtype = np.float64)

In [65]: y = np.around(x, decimals = 3)

In [66]: y
Out[66]: array([ 73.34,  73.34])

请注意,即使打印的
y
表示为73.34,实数73.34也不一定可以精确表示为浮点数64。float64表示法可能非常接近73.34,以至于NumPy选择将其打印为73.34。

由@unutbu给出的答案绝对正确。Numpy正在根据您要求的精度将其舍入到尽可能接近的数字。我唯一需要补充的是,您可以使用更改数组的显示方式:

>>> import numpy as np
>>> x = np.array([73.33999634, 73.340], dtype = np.float32)
>>> y = np.round(x, decimals = 3)
>>> y
array([ 73.33999634,  73.33999634], dtype=float32)
>>> np.set_printoptions(precision=3)
>>> y
array([ 73.34,  73.34], dtype=float32)

但是双浮点不是应该有更大的粒度吗?一个
float64
是一个8字节的浮点。因此,它可以表示比
float32
更多的数字。更多的数字意味着更小的粒度。是的,我的意思是更细或更好的粒度(越大的粒度总是越大:)。。(语言的特殊性)。。但无论如何,我认为浮动64更好。谢谢大家!酷,我没听说过!但这不会改变输入数据,我打算这样做。。