简体   繁体   English

使用Numpy在Python中使用浮点数舍入错误

[英]Rounding errors with floats in Python using Numpy

I'm having an issue that I believe has to do with working with floats and precision but I'm not very well versed in the various intricacies involved. 我有一个问题,我认为与使用花车和精度有关,但我不太熟悉所涉及的各种错综复杂的问题。 I'm a math person and in my mind I might as well still be just working with decimals on a chalkboard. 我是一个数学家,在我的脑海里,我可能仍然只是在黑板上使用小数。 I'll begin studying up on this, but in the mean time, I'm wondering if there are any general techniques for working with floats that might address the problem I'll outline below. 我将开始研究这个,但同时,我想知道是否有任何一般的技术来处理可能解决我将在下面概述的问题的浮点数。

I have a numpy array of decimals that I would like to round to the nearest .02. 我有一个小数组的小数,我想舍入到最近的.02。 I originally accomplished this by dividing every element of the array by .02, rounding the result, then multiplying by .02 again. 我最初通过将数组的每个元素除以.02,舍入结果,然后再次乘以.02来完成此操作。 The actual data is generated by some code that process an input, but this demonstrates the problem: 实际数据是由处理输入的一些代码生成的,但这证明了问题:

x = np.array([.45632, .69722, .40692])
xx = np.round(x/.02)*.02

It seems to round everything correctly, as I can check: 它似乎正确地围绕一切,因为我可以检查:

xx
array([0.46, 0.7, 0.4])

However, if I inspect the first and second element, I get: 但是,如果我检查第一个和第二个元素,我得到:

xx[0]
0.46000000000000002
xx[1]
0.70000000000000007

Each element in the array is of type numpy.float64. 数组中的每个元素都是numpy.float64类型。 The problem occurs later because I involve these numbers with comparison operators to select subsets of the data and what happens then is a little unpredictable: 这个问题后来发生,因为我将这些数字与比较运算符一起用于选择数据的子集,然后发生的事情有点不可预测:

xx[0] == .46
True

But, 但,

xx[1] == .70
False

As I said, I have a work around for this particular application, but I'm wondering if anyone has a way to make my first approach work or if there are techniques for dealing with these types of numbers that are more general that I should be aware of. 正如我所说,我有一个解决这个特定应用程序的工作,但我想知道是否有人有办法让我的第一个方法工作,或者是否有技术来处理这些类型的数字更普遍,我应该是意识到。

Rather than using == to select subsets of data, try using numpy.isclose() . 而不是使用==来选择数据子集,请尝试使用numpy.isclose() This allows you to specify a relative/absolute tolerance for your comparison (absolute(a - b) <= (atol + rtol * absolute(b))) 这允许您为比较指定相对/绝对容差(absolute(a - b) <= (atol + rtol * absolute(b)))

Python's format could be used for this too. Python的format也可以用于此。

print format(xx[1], '.100f')

this code return actual value of xx[1] 此代码返回xx[1]实际值xx[1]

ie. 即。 xx[1] = 0.70000000000000006661338147750939242541790008544921875

You can check these by code shown below 您可以通过以下代码检查这些

if xx[1] == 0.70000000000000006661338147750939242541790008544921875:
    print 'true'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM