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

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

问题描述

我的 Matlab 版本是 R2012a
为什么在 Matlab 1.1-0.2 中不等于 0.9!!!!!!
这太可怕了!

<块引用>

>>1.1-0.2 == 0.9

ans =

<代码> 0

解决方案

这不是 Matlab 问题;这是一个浮点问题.您将在 C++(或任何符合 IEEE754 就此而言):

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

输出:

<预><代码>0

这是因为 1.1 和 0.9 不能完全用二进制表示.这就像用十进制表示 1/3:你必须写

0.33333333333333333333333333333333333333333333333...

并无限期地继续.但无论你坚持多久,你永远不会做对.

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

<代码>>>1.1-0.2答案 =9.000000000000001e-01

这很接近,但不完全正确.

正因如此,在使用==比较两个浮点数之前,你应该三思而后行;很少有 == 运算符可以在没有像您刚刚遇到的那种奇怪"后果的情况下应用.

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

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

其中 eps 是一个 Matlab 函数,它返回 spacing-用于特定双精度值的双精度之间.但实际上,这并不是一个包罗万象的解决方案.正确比较浮点数是一件棘手的事情.

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

ans =

 0

解决方案

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;
}

output:

0

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)

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天全站免登陆