Problem with loop for
3 次查看(过去 30 天)
显示 更早的评论
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)])
%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)])
3 个评论
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
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_sred2 = sum(x)/N
disp(['x_sred1 = ' ,string(x_sred1), 'x_sred2 = ' ,string(x_sred2)])
%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)])
回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!