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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by