フィルターのクリア

Find not finding number in vector

2 ビュー (過去 30 日間)
Jon
Jon 2016 年 6 月 21 日
編集済み: John D'Errico 2016 年 6 月 21 日
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
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
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
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

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by