2つの値の違いがわからない

12 views (last 30 days)
yuta
yuta on 5 Jul 2022
Commented: yuta on 9 Jul 2022
Aとstartの中身が私には同じに見えますが、同様の処理をしても結果が異なります。
なぜこのような違いが生じるのかご教示いただければ幸いです。
load('A.mat')
A
A = 1×10
7.8200 7.0230 8.0540 7.8640 7.6350 7.3300 7.6600 7.8630 7.9130 9.0220
load('start.mat')
start
start = 1×10
7.8200 7.0230 8.0540 7.8640 7.6350 7.3300 7.6600 7.8630 7.9130 9.0220
load('B.mat')
C = find(B == A(1));
C
C = 7820
D = find(B == start(1));
D
D = 1×0 empty double row vector

Accepted Answer

Kojiro Saito
Kojiro Saito on 5 Jul 2022
出力の表示形式で値が丸め込まれて見えているのが原因です。
こちらのドキュメントに詳細がありますが、MATLABではデフォルトでshortの表示形式なので、小数点以下が4桁の固定小数点形式で表示されます。
実はA(1)とstart(1)では同じ値になっていません(A(1) == start(1)がfalseの0になります)。
load('A.mat')
A(1)
ans = 7.8200
load('start.mat')
start(1)
ans = 7.8200
A(1) == start(1)
ans = logical
0
桁数を増やして表示すると、A(1)とstart(1)で値が違っているのが確認できます。
format long
A(1)
ans =
7.820000000000000
start(1)
ans =
7.819999999999999
  6 Comments
Kojiro Saito
Kojiro Saito on 7 Jul 2022
==のドキュメントに「小数のテキストで表された多くの数値は、2 進浮動小数点数として正確に表すことができません。これにより、== 演算子が反映する結果に若干の違いが生じます。」とあります。
以下はroundを使ってみた例です。
tind = [1:10000]/1000;
tindA = tind +0.01;
A = 8.271;
B = find(round(tind, 3) == A )
B = 8271
C = find(round(tindA, 3) == A )
C = 8261
yuta
yuta on 9 Jul 2022
時間軸もroundで丸めこんでしまえばいいんですね!ありがとうございます。

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!