How do I avoid errors due to round-off in Matlab?

6 ビュー (過去 30 日間)
Monisha S R
Monisha S R 2018 年 10 月 15 日
編集済み: Bruno Luong 2018 年 10 月 15 日
My code produces round-off errors which I cannot seem to correct even by using vpa(variable). The code gives Nt = 888890 whereas the length(t) = 888889. How do I resolve this discrepancy? I need Nt (number of nodes) to be an integer and the formula for Nt is correct. Any help would be appreciated. Thanks.
dt = 0.0225; tend = 20000;
Nt = round(tend/dt +1);
t = (0:dt:tend)';

採用された回答

Bruno Luong
Bruno Luong 2018 年 10 月 15 日
t=linspace(0,tend,Nt);
  3 件のコメント
Bruno Luong
Bruno Luong 2018 年 10 月 15 日
編集済み: Bruno Luong 2018 年 10 月 15 日
Because of round-off error as you say. Basically the column syntax increment sequentially from the start value with the given step and go on while the current value <= the specified end value.
Because of round off, it end up slightly larger than 20000 at the step 888890, so this value is not kept.*
Linspace just divides the interval in (n-1) equal parts to get exactly n points, always.
(*) actually there are some special treatment by doing both directions by columns, but for simplicity of the explanation I don't go into the detail of that procedure.
Bruno Luong
Bruno Luong 2018 年 10 月 15 日
編集済み: Bruno Luong 2018 年 10 月 15 日
The round-off occurs because 0.0225 = (9/16)*(1/5)*(1/5) and because 1/5 cannot be stored exactly on finite binary, it actually cannot be represented exactly on the computer, so is not 0.0225.
If you try with step for example 0.1250 = 1/8, this problem does not occur, or similar with 0.0625 = 1/16 or 0.03125. I cut my hand if the problem happens with those steps.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by