MOD function fails to give correct answer
4 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Walter Roberson
on 13 Apr 2012
4.0000 does not mean "exactly 4": it means "between 3.99995 and 4.00005"
2 Comments
Walter Roberson
on 13 Apr 2012
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
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!