Different machine precision for scalars and vectors?

조회 수: 1 (최근 30일)
Victoria Interrante
Victoria Interrante 2020년 8월 31일
댓글: Victoria Interrante 2020년 8월 31일
I was prearing a demonstration for my students on the topic of numerical error, and after some trial and error devised the sequence:
for i = 1:8
a = sin(i*(pi/2))
end
which reveals errors due to machine precision (a ≠ 0) when i is even. However, these errors do not show up if I store the result in a vector:
for i = 1:8
a(i) = sin(i*(pi/2))
end
Can anyone explain why? I'm guessing the reason is that somehow fewer bits are being used to encode the fractional part of the number in the latter case, but it's not clear to me why this would be the case.
  댓글 수: 1
David Hill
David Hill 2020년 8월 31일
It is the same answer.
format long
a=sin(pi);
b=sin((1:8)*pi/2);
display(b(2));

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2020년 8월 31일
The only difference is the display in the command window. Matlab tries to display vectors in an abbreviated format, execpt if you instruct it to show the full precision. David Hill suggested format long g already. Then you see, that storing the values in a vector does not change the accuracy.

추가 답변 (1개)

the cyclist
the cyclist 2020년 8월 31일
If you don't have a specific reason to be using a for loop here, why not also teach them canonical use of vectorized calculations?
i = 1:8;
a(i) = sin(i*(pi/2))
And either use the advice in David Hill's comment, or subtract the exact answer from a to show the error:
exact = [1 0 -1 0 1 0 -1 0];
floatingPointError = a - exact

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by