MATLAB Answers

Why the sums of cos(x) over 2*pi range not zero?

9 ビュー (過去 30 日間)
Tianyou Chen
Tianyou Chen 2012 年 7 月 11 日
when evaluating the following codes:
t = linspace(-pi,pi,128); s = sin(t); c = cos(t); sum(s), sum(c)
ans =
6.811558403281303e-15
ans =
-0.999999999999978
Q: should not both be zero?
and try
sum(c(2:end))
ans =
2.5313e-14
also quad(@cos,-pi,pi)
ans =
4.0143e-09
Q: Why the discrepancy?
Thank you for your input.
Thanks J

  0 件のコメント

サインイン to comment.

採用された回答

Greg Heath
Greg Heath 2012 年 7 月 11 日
T = fundamental period
N = number of samples
dt = T/N sampling interval
f0 = 1/T fundamental frequency
(n-1)*f0 harmonics 1<=n <= N
Orthogonality interval
t = t0:dt:t0+T-dt;
t = t0+[0:dt:T-dt];
t = t0+dt*[0:N-1];
help fft
doc fft
Hope this helps
Greg

  2 件のコメント

Greg Heath
Greg Heath 2012 年 7 月 11 日
t = t0 + linspace(0,T-dt,N);
t = t0 + dt*linspace(0,N-1,N);
Tianyou Chen
Tianyou Chen 2012 年 7 月 11 日
Thanks Greg. It makes sense now. J

サインイン to comment.

More Answers (3)

Luffy
Luffy 2012 年 7 月 11 日
In matlab,
sin(pi) = 1.2246e-16
The expression sin(pi) is not exactly zero because pi is not exactly π

  0 件のコメント

サインイン to comment.


Wayne King
Wayne King 2012 年 7 月 11 日
編集済み: Wayne King 2012 年 7 月 11 日
If you're trying to establish some equivalence between the integral of cos(t) from -pi and pi and the sum of cos(t), you're forgetting a very important part and that is the dt
t = linspace(-pi,pi,1000);
dt = (pi-(-pi))/length(t);
sum(cos(t))*dt
Using other integration routines in MATLAB is more robust than what I've done, but you see it gets you much closer to zero. Think about the formula for a Riemann sum.

  1 件のコメント

Tianyou Chen
Tianyou Chen 2012 年 7 月 11 日
Hi Wayne,
Thanks for the answer. But I don't think dt is the issue. try this and nyou will know what I mean: t1 = linspace(-pi,0,64); t2 = linspace(0,pi,64); c1 = cos(t1); c2 = cos(t2); sum(c1) sum(c2)
ans =
-4.4409e-16
ans =
5.7732e-15
or t1 = linspace(0,pi,64); t2 = linspace(pi,2*pi,64);
c1 = cos(t1); c2 = cos(t2); sum(c1) sum(c2)
ans =
5.7732e-15
ans =
-1.1102e-14
Thus with or without dt, the sum of a sin or cos over a period of 2pi should be zero. Here the sin function gives the correct answer. I suspect that the even nature of the cos fuction may have something to do with its suming over (-pi, pi) is -1 while over (0,2*pi) is +1.

サインイン to comment.


Wayne King
Wayne King 2012 年 7 月 11 日
I don't think you can say that simply summing cos(t) on an arbitrary grid should be zero. You have to be careful how the grid is constructed. For example
k = 1;
N = 100;
t = 0:99;
sum(cos(2*pi*k/N*t))
sum(sin(2*pi*k/N*t))
are both zero, because I used a Fourier frequency and a specific discrete-time vector. This has to do with the orthogonality of the N-th roots of unity.

  1 件のコメント

Tianyou Chen
Tianyou Chen 2012 年 7 月 11 日
Thank Wayne,
You are correct and I should have caught that - the discrete nature of the signal. Cheers, J

サインイン to comment.

サインイン してこの質問に回答します。


Translated by