I have a simple code like this
t = 1380;
dt = 0.1
for i = 1:1000
t = t+dt;
disp(t)
end
I believe the answer should be obvious that the final answer should be
t = 1480. I dont know why Matlab shows the answer a little bit different which is 1479.99999999991.
Anyone know why?

回答 (1 件)

Star Strider
Star Strider 2019 年 11 月 13 日

2 投票

You have encountered floating-point approximation error.
See the documentation section on Floating-Point Numbers, and the colon operator.

3 件のコメント

Obaja Triputera Wijaya
Obaja Triputera Wijaya 2019 年 11 月 18 日
Is there anything that we can do? because inside the loop, I would like to add If statement.
if t == 1400
a = 2
end
but the problem is the t nver reach that value because of the floating error
Star Strider
Star Strider 2019 年 11 月 18 日
Yes.
Change it to:
if abs(t - 1400) < 0.05
a = 2
end
Since the code counts up by ‘dt’, this will introduce a tolerance in the calculation, so the floating-point approximation error are taken into account.
To see this graphically:
t = linspace(1399, 1401);
figure
plot(t, (abs(t - 1400) < 0.05))
grid
That will show the effect of using the inequality to test for a range of values for ‘t’ near 1400.
Experiment to get the result you want.
darova
darova 2019 年 11 月 18 日
Don't use equal sign for float numbers
if abs(t-1400) < 1e-6 % tolerance
a = 2;
end

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2019 年 11 月 13 日

コメント済み:

2019 年 11 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by