필터 지우기
필터 지우기

Problem with loop for

조회 수: 1 (최근 30일)
Joanna Zajac
Joanna Zajac 2024년 3월 6일
댓글: VBBV 2024년 3월 8일
Hello
I need to calculate average value using various methods including loop for. I don't know why result using loop is diffrent. Can someone help with that?
N = 1200;
A = 2;
fx = 5;
fp = 1000;
dt = 1/fp;
t = dt*(0:N-1);
x = A*sin(2*pi*fx*t);
x_sred1 = mean(x); %average value
x_sred2 = sum(x)/N;
disp(['x_sred1 = ' ,string(x_sred1), 'x_sred2 = ' ,string(x_sred2)])
"x_sred1 = " "-1.3414e-16" "x_sred2 = " "-1.3414e-16"
%average value loop for
l=length(x);
s_x=0;
for i=1:l
s_x=s_x+x(i);
end
x_sred3=s_x/N;
disp(['x_sred3 = ' ,string(x_sred3)])
"x_sred3 = " "9.142e-17"
  댓글 수: 3
Mathieu NOE
Mathieu NOE 2024년 3월 6일
No , the code is correct in its principle, but your for loop demonstrate that this method is accumulating more errors than the two first methods
with the choosen parameters , your sum should be zero , but you see actually some difference (as tiny numbers) because of round off accumated errors.
now if you can make a small change in your parameters to get a sum that is not (almost) zero , then all 3 computations are very close.
here for example I simply change N from 1200 to 1150 and I get :
"x_sred1 = " "0.056223" "x_sred2 = " "0.056223"
"x_sred3 = " "0.056223"
or N = 1200 and fp = 5000 (to increase time accuracy)
"x_sred1 = " "0.1825" "x_sred2 = " "0.1825"
"x_sred3 = " "0.1825"
VBBV
VBBV 2024년 3월 8일
@Joanna Zajac, It is something to do with property of sin function for specific values in input array
N = 1200;
A = 2;
fx = 5;
fp = 1000;
dt = 1/fp;
t = dt*(0:N-1);
x = A*(2*pi*fx*t);
x_sred1 = mean(x) %average value
x_sred1 = 37.6677
x_sred2 = sum(x)/N
x_sred2 = 37.6677
disp(['x_sred1 = ' ,string(x_sred1), 'x_sred2 = ' ,string(x_sred2)])
"x_sred1 = " "37.6677" "x_sred2 = " "37.6677"
%average value loop for
% l=length(x);
s_x=0;
for i=1:numel(x)
s_x=s_x+x(i);
end
x_sred3=s_x/N;
disp(['x_sred3 = ' ,string(x_sred3)])
"x_sred3 = " "37.6677"

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

답변 (1개)

Image Analyst
Image Analyst 2024년 3월 6일
편집: Image Analyst 2024년 3월 6일
This is round-off error, a form of quantization error. See
and
for explanations.
They should have taught you this in your numerical analysis class or linear algebra (matrix) class. Hopefully you have taken such a class in college.

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by