Matlab精度:简单减法不为零 [英] Matlab precision: simple subtraction is not zero

查看:263
本文介绍了Matlab精度:简单减法不为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Matlab上计算了这个简单的和:

$ p $ 2 $ 0.04-0.5 * 0.4 ^ 2 = -1.387778780781446e-017

但结果不为零。我能做什么?

解决方案

通常情况下,不是精确地计算2 * 0.04 - 0.5 * 0.4 ^ 2的值,您真正想要的是检查2 * 0.04和0.5 * 0.4 ^ 2之间的差异是否足够小在相关的数值精度范围内。如果是这样,而不是检查 2 * 0.04 - 0.5 * 0.4 ^ 2 == 0 是否可以检查 abs(2 * 0.04 - 0.5 * 0.4 ^ 2)脱粒。这里 thresh 可以是一些任意的小数字,或者是一个涉及 eps 的表达式,它给出了数字类型的精度你正在使用。

编辑:
感谢Jim和Tal提出的改进建议。改变比较的差异的绝对值的门槛,而不是差异。


I compute this simple sum on Matlab:

2*0.04-0.5*0.4^2 = -1.387778780781446e-017

but the result is not zero. What can I do?

解决方案

Aabaz and Jim Clay have good explanations of what's going on.

It's often the case that, rather than exactly calculating the value of 2*0.04 - 0.5*0.4^2, what you really want is to check whether 2*0.04 and 0.5*0.4^2 differ by an amount that is small enough to be within the relevant numerical precision. If that's the case, than rather than checking whether 2*0.04 - 0.5*0.4^2 == 0, you can check whether abs(2*0.04 - 0.5*0.4^2) < thresh. Here thresh can either be some arbitrary smallish number, or an expression involving eps, which gives the precision of the numerical type you're working with.

EDIT: Thanks to Jim and Tal for suggested improvement. Altered to compare the absolute value of the difference to a threshold, rather than the difference.

这篇关于Matlab精度:简单减法不为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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