Why mod(19, nRun) where nRun is 19, is not equal to 0?

1 次查看(过去 30 天)
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?
  1 个评论
Stephen23
Stephen23 2023-8-8
编辑:Stephen23 2023-8-8
"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
ans = logical
1
"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
ans = 2.2027e-12
This is a completely expected result or arithmetic using binary floating point numbers:
This is worth reading as well:

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2023-8-8
format long g
yieldLoss = 1 - 0.9999
yieldLoss =
9.9999999999989e-05
yieldLoss == 0.0001
ans = logical
0
yieldLoss - 0.0001
ans =
-1.10182045778839e-17
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)
0.1000000000000000055511151231257827021181583404541015625
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 个)

类别

Help CenterFile Exchange 中查找有关 GPU Computing 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by