Why mod(19, nRun) where nRun is 19, is not equal to 0?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I found a strange behavior regarding the matlab modulus function where I hope the Mathworks community is able to help explain and provide suggestions on how to overcome this.
Why is mod(19,nRun), where nRun = 19, is not 0 and instead output 19?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1453027/image.png)
1 commentaire
Stephen23
le 8 Août 2023
Modifié(e) : Stephen23
le 8 Août 2023
"Why mod(19, nRun) where nRun is 19, is not equal to 0?"
Actually it is. Lets try it right now:
mod(19,19)==0
"I found a strange behavior regarding the matlab modulus function..."
What you found has nothing to do with the MOD function.
It is caused by the fact that your nRun is not exactly equal to 19. Lets try it right now:
yl = 1 - 0.9999; % not 0.0001 (this does not exist)
lpr = yl * 500; % not 0.05
nrpl = 1/lpr; % not 20
nr = nrpl - 1; % not 19
nr-19 % nope, definitely not 19
This is a completely expected result or arithmetic using binary floating point numbers:
This is worth reading as well:
Réponse acceptée
Walter Roberson
le 8 Août 2023
format long g
yieldLoss = 1 - 0.9999
yieldLoss == 0.0001
yieldLoss - 0.0001
MATLAB does not operate in decimal: it operates in binary double precision, using industry standard IEEE 754 Double Precision Floating Point numbers
Unfornately it is not possible for any finite-length double-precision floating point system to represent recipricals of powers of 10 exactly .
fprintf('%.9999g\n', 0.1)
This is not a bug in MATLAB: this is a fundamental mathematical limitation using finite representation with any numeric base that is not a multiple of 5.
Switching to decimal would not fix all such problems: it would just change them. For example suppose you use 4 digit decimal representation, then consider 1/3 --> 0.3333 . Now multiply that by 3, and you are going to get 0.9999 . So in any finite-length decimal representation, 1/3 * 3 will not be exactly 1. In any finite-length decimal representation, 1/7 * 7 will not be exactly 1, 1/11 * 11 will not be exactly 1, and so on. It is mathematically impossible to use finite-precision representation in any fixed numeric base and not have these kinds of problems.
How does Mathematics avoid these problems? Well, Mathematics such as the rational numbers does not use finite precision
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur GPU Computing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!