Weird result, why I can't find -0.809 and 0.309 in -1:0.001:1???

1 次查看(过去 30 天)
why I can't find -0.809 and 0.309 in -1:0.001:1???

采纳的回答

David Goodmanson
David Goodmanson 2020-3-4
编辑:David Goodmanson 2020-3-4
Hello JX,
you are looking for exact equality with floating point numbers, and a exact equality does not always occur.
x = -1:.001:1;
format long
x(1810)
ans = 0.809000000000000 % looks good
x(1810) - .809
ans = -1.110223024625157e-16 % isn't good
Since there are only a finite number of bits (64 for double precision numbers like these), most floating point numbers cannot be stored exactly in memory. Here there is disagreement in the 16th decimal place, which is to be expected in some (not all) of the 2001 cases for the x array.
If you take a look with format hex, the way these numbers are actually stored,
>> format hex
x(1810)
ans = 3fe9e353f7ced916
809
ans = 3fe9e353f7ced917
you can see that first, .809 is stored as well as possible with 64 bits but not exactly (as would be the case with a bunch of trailing hex zeros), and second that the two numbers differ by 1 in the last bit. The equality check fails.
  3 个评论
Stephen23
Stephen23 2020-3-4
"How can I find -0.809 and 0.309 in -1:0.001:1?"
Never compare binary floating point values for exact equality.
Always compare the absolute difference against a tolerance, e.g.:
tol = 1e-5;
idx = abs(A-B)<tol
Steven Lord
Steven Lord 2020-3-4
Another way to compare with a tolerance is to use ismembertol.
>> ismembertol(-0.809, -1:0.001:1, eps)
ans =
logical
1
If I'd used a tolerance of 0 as the third input, to only detect cases where -0.809 is an exact down-to-the-last-bit match for an element in the vector, the answer would have been false (logical 0.)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by