# Problem with loop for

4 vues (au cours des 30 derniers jours)
Joanna Zajac le 6 Mar 2024
Commenté : VBBV le 8 Mar 2024
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 commentairesAfficher 1 commentaire plus ancienMasquer 1 commentaire plus ancien
Mathieu NOE le 6 Mar 2024
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 le 8 Mar 2024
@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"

Connectez-vous pour commenter.

### Réponses (1)

Image Analyst le 6 Mar 2024
Modifié(e) : Image Analyst le 6 Mar 2024
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 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Linear Algebra dans Help Center et File Exchange

R2023b

### Community Treasure Hunt

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

Start Hunting!

Translated by