使用Numpy在Python中使用浮点舍入错误 [英] Rounding errors with floats in Python using Numpy

查看:166
本文介绍了使用Numpy在Python中使用浮点舍入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个与浮点数和精度有关的问题,但是我对所涉及的各种复杂性不是很精通.我是一个数学人,在我的脑海中,我仍然可能只在黑板上使用小数.我将开始对此进行研究,但与此同时,我想知道是否有用于处理浮点数的通用技术可以解决我将在下面概述的问题.

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.

我有一个小数的numpy数组,我想四舍五入到最接近的.02.我最初是通过将数组的每个元素除以.02,对结果取整,然后再次乘以.02来实现的.实际数据是由一些处理输入的代码生成的,但这证明了问题所在:

I have a numpy array of decimals that I would like to round to the nearest .02. I originally accomplished this by dividing every element of the array by .02, rounding the result, then multiplying by .02 again. 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

数组中的每个元素的类型为numpy.float64.问题稍后出现,因为我将这些数字与比较运算符结合在一起以选择数据的子集,然后发生的事情有点不可预测:

Each element in the array is of type 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

但是

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(). This allows you to specify a relative/absolute tolerance for your comparison (absolute(a - b) <= (atol + rtol * absolute(b)))

这篇关于使用Numpy在Python中使用浮点舍入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆