Why does dividing and multiplying by the same number cause a numerical error?
이전 댓글 표시
What is is that causes a numerical error when dividing and multiplying by the same number? For instance,
format long
13/1e5*1e5
gives
12.999999999999998
I'm shouldn't be running out of double precision floating point room, should I?
Incidentally,
13/sqrt(2)*sqrt(2)
works fine.
For 1e5, let's display a list of all the numbers that don't work between 1 and 100:
myNumbers = [];
sr = 1e5
for i = 1:100
if (i/sr*sr-i) ~= 0
myNumbers(end+1) = i;
end
end
myNumbers
this returns:
7 13 14 15 26 28 30 51 52 56 60
I'll live with it, but I'm just curious if it's something I should have expected...
cheers,
Will
답변 (2개)
Azzi Abdelmalek
2015년 3월 3일
0 개 추천
Standard rules for operator precedence, also used by MATLAB, state that multiplication and division are on the same precedence level, and that within each precedence level operators have equal precedence and are evaluated from left to right_So
13 / 1e5 * 1e5
will be evaluated as
(13 / 1e5) * 1e5
Lets have look at the result of the first part (the intermediate result):
>> fprintf('%.30f\n', 13/1e5)
0.000129999999999999990000000000
Which should answer your question: the value of 13/1e5 is not exactly representable by a double data type. Welcome to the world of numeric mathematics!
댓글 수: 1
James Tursa
2015년 3월 3일
FYI, fprintf and sprintf (at least on a PC) do not show the exact decimal conversion of a floating point number, they only show a rounded version of it. To see the exact decimal conversion one has to use other methods, e.g. using the symbolic toolbox or using the num2strexact utility:
>> fprintf('%.60f\n',13/1e5)
0.000129999999999999990000000000000000000000000000000000000000 <-- rounded
>> num2strexact(13/1e5)
ans =
1.2999999999999998861154038021226142518571577966213226318359375e-4
>> num2strexact(13/1e5*1e5)
ans =
1.29999999999999982236431605997495353221893310546875e1
You can find num2strexact here:
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!