Sum of two numbers is not accepted

1 回表示 (過去 30 日間)
Stanislav Kotsmid
Stanislav Kotsmid 2020 年 7 月 30 日
回答済み: Sriram Tadavarty 2020 年 7 月 30 日
Hi everyone,
I have a problem with deleting numbers in a matrix. Let's have a matrix M, where I want to delete all rows with a specified value in the second column, e.g:
M(M(:,2)==0.141,:)=[];
All rows with 0.141 in the second column are now deleted.
Also, I tried to specify this value by a sum of two numbers:
a=0.14+0.001;
M(M(:,2)==a,:)=[];
This sum hasn't been accepted and all values are still in the matrix.
Can anyone explain me this mysterious thing please?

採用された回答

KSSV
KSSV 2020 年 7 月 30 日
編集済み: KSSV 2020 年 7 月 30 日
Read about comparing two floating-point numbers.
a=0.14+0.001;
tol = 10^-5 ;
idx = abs(M(:,2)-a)<=tol ;
M(idx,:)=[];

その他の回答 (1 件)

Sriram Tadavarty
Sriram Tadavarty 2020 年 7 月 30 日
Hi Stanislav,
It is the way the floating point airthmetic are performed in MATLAB.
If you would have tried 0.14 + 0.001 equals 0.141, then you would have seen both doesn't match.
There were similar posts in this forum regarding this. One such which i recently encountered has lot more detailed links. https://www.mathworks.com/matlabcentral/answers/572680-is-there-a-bug-in-the-if-function
Also, inorder to avoid common problems using airthmetic floating point numbers, have a look here.
For the problem here, place a tolerance and then it would provide same results, as expected.
Thanking you.
Regards,
Sriram

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by