这是Matlab的错误吗?你有同样的问题吗? [英] Is this a Matlab bug? Do you have the same issue?

查看:52
本文介绍了这是Matlab的错误吗?你有同样的问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Matlab版本是R2012a
为什么在Matlab 1.1-0.2中不等于0.9 !!!!!?
太糟糕了!

My Matlab version is R2012a
Why in Matlab 1.1-0.2 is not equal to 0.9!!!!!?
This is awful!

>> 1.1-0.2 == 0.9

>>1.1-0.2 == 0.9

ans =

 0

推荐答案

这不是Matlab问题;这是一个浮点问题.您将在C ++(或符合 IEEE754 的任何编程语言)中获得相同的结果>):

It is not a Matlab issue; it is a floating point issue. You'll get the same result in C++ (or any programming language that conforms to IEEE754 for that matter):

#include <iostream>    
int main(int, char **) {
    std::cout << (1.1-0.2==0.9) << std::endl;
    return 0;
}

输出:

0

这是因为1.1和0.9 无法完全用二进制表示.就像用小数表示1/3:您必须编写

This is because 1.1 and 0.9 cannot be represented exactly in binary. It's like expressing 1/3 in decimal: you'll have to write

0.33333333333333333333333333333333333333333333333...

,然后无限期地继续.但是,无论您持续多长时间,都永远无法做到正确.

and continue indefinitely. But no matter how long you continue, you'll never get it right.

在浮点中,您只能存储太多数字,因此计算必须在某处停止.计算结果实际上是

In floating point, you only have so many digits you can store, so the calculation will have to stop somewhere. The result of the calculation is actually

>> 1.1-0.2
ans =
     9.000000000000001e-01

这很接近,但不太正确.

which is pretty close, but not quite correct.

因此,在使用==比较两个浮点数之前,您应该三思而后行.很少可以使用==运算符而不会像您刚遇到的那样产生一些奇怪"的后果.

Because of this, you should always think twice before using == to compare two floating-point numbers; it is rare that the == operator can be applied without some "strange" consequences like the one you just encountered.

最好使用四舍五入的特定公差,例如

It is better to use a round-off specific tolerance, like

abs(1.1-0.2 - 0.9) <= eps(0.9)

其中eps是Matlab函数,它返回 spacing-between-doubles 表示特定的double值.但是,实际上,这不是万能的解决方案.正确比较浮点数是一件棘手的事情.

where eps is a Matlab function which returns the spacing-between-doubles for a specific double value. But really, this is not a catch-all-end-all solution; correctly comparing floating points is a tricky business.

这篇关于这是Matlab的错误吗?你有同样的问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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