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