MOD function fails to give correct answer

4 ビュー (過去 30 日間)
Laurentiu
Laurentiu 2012 年 4 月 13 日
Hi y'all.
I've just run into this problem. While trying to update a signal every 4 seconds, the following strange results showed up which prevented me from correct updates.
simu_step = 0.0100, t_current = 3.9700, timeinterval_agc = 4.0000, mod(t_current, timeinterval_agc) = 3.9700 ======================================================
simu_step = 0.0100, t_current = 3.9800, timeinterval_agc = 4.0000, mod(t_current, timeinterval_agc) = 3.9800 ==============================================================
simu_step = 0.0100, t_current = 3.9900, timeinterval_agc = 4.0000, mod(t_current, timeinterval_agc) = 3.9900 ==============================================================
simu_step = 0.0100, t_current = 4.0000, timeinterval_agc = 4.0000, mod(t_current, timeinterval_agc) = 4.0000 ==============================================================
simu_step = 0.0100, t_current = 4.0100, timeinterval_agc = 4.0000, mod(t_current, timeinterval_agc) = 0.0100 ==============================================================
simu_step = 0.0100,t_current = 4.0200, timeinterval_agc = 4.0000, mod(t_current, timeinterval_agc) = 0.0200 ==============================================================
As you can see, everything seems to be all right, except that mod(4, 4) = 4 and not 0. Though I am sure I can find a way to get around it, I still cannot understand why MATLAB would give such a strange answer.
Any ideas?
Thanks --Laurentiu

採用された回答

Walter Roberson
Walter Roberson 2012 年 4 月 13 日
4.0000 does not mean "exactly 4": it means "between 3.99995 and 4.00005"
  2 件のコメント
Walter Roberson
Walter Roberson 2012 年 4 月 13 日
Advice: do not increment t_current by 0.01 each time. Instead, increment a variable by 1 each time, and compute t_current as the variable / 100
Laurentiu
Laurentiu 2012 年 4 月 13 日
Thanks a lot, Walter. Will try your suggestion.
Funny thing about it is that the operation fails for t_current = 4, 8, 16, but is successful for t_current = 20. That's what actually made me think initially that my code was working, but surprised me when I went to check it in details.
Thanks a lot for your prompt answer.

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by