I have "figured" this out. x(533)-43.2 = -7.105427357601e-15. Now that I'm searching "find doesn't work" it appears this problem comes up quite a lot. I feel that this is probably something that should be fixed.
Find not finding number in vector
1 次查看(过去 30 天)
显示 更早的评论
If I do
x = -10:.1:90;
find(x==43.2)
I get
ans =
Empty matrix: 1-by-0
If I do
x(533) == 43.2
I get zero. Does anyone have any idea why this would happen? 43.2 is clearly in the vector. If x = 0:.1:44 it can find 43.2.
4 个评论
Stephen23
2016-6-21
编辑:Stephen23
2016-6-21
@Jon: what exactly do you want to "fix"... nothing is broken! This is exactly how binary floating point numbers are, and it is correct.
Decimal numbers with finite digits cannot represent all possible real numbers, so why do you expect binary floating point numbers to be able to do this?
For example, can you show me an exact representation of 1/3, by using just four decimal digits? If you can then I will show you how to write 0.1 exactly using a double! This is a fun game because it is impossible: it makes no mathematical sense at all to try to "fix" it: how would you "fix" 1/3 using four decimal digits?
If you really want to "fix" it, then invent a totally new computer system that stores infinite digits of precision.
John D'Errico
2016-6-21
编辑:John D'Errico
2016-6-21
Or, I suppose you might decide to store all numbers in decimal form instead of binary. After all, this would "solve" the current problem.
Hmm, I wonder why that is not the choice made? (A Socratic question.)
Computers use binary storage to store numbers for many reasons.
1. Decimal storage would be inefficient in terms of memory. Have you ever seen someone seriously complaining they had too much memory on their computer?
2. Computations will be faster for numbers stored in binary then in decimal. Have you ever seen someone seriously wanting their computer to run more slowly?
3. Suppose you did use decimal storage for all numbers. There would now be some numbers that were previously stored with an exact representation in binary that are now no longer exactly stored as decimal. Pick ANY finite floating point representation. Some numbers will not be exactly representable. You can't win.
The point is, you cannot just "fix" the problem, at least not without creating other problems that are just as bad or worse. You can fix the problem of not understanding how to work with floating point numbers.
回答(1 个)
KSSV
2016-6-21
编辑:KSSV
2016-6-21
You should never use the == operator when comparing float/double values. You should check that the difference is < or > than a given threshold e.g. 0.001
You may refer the link for further information: http://matlabgeeks.com/tips-tutorials/floating-point-comparisons-in-matlab/
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!