필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
Remy
Remy 2023년 8월 8일
편집: Stephen23 2023년 8월 8일
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