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

조회 수: 6 (최근 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 =
ans =
Q: should not both be zero?
and try
ans =
also quad(@cos,-pi,pi)
ans =
Q: Why the discrepancy?
Thank you for your input.
Thanks J

채택된 답변

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
  댓글 수: 2
Tianyou Chen
Tianyou Chen 2012년 7월 11일
Thanks Greg. It makes sense now. J

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

추가 답변 (3개)

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

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);
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 =
ans =
or t1 = linspace(0,pi,64); t2 = linspace(pi,2*pi,64);
c1 = cos(t1); c2 = cos(t2); sum(c1) sum(c2)
ans =
ans =
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.

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

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;
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

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


Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by