sum of series. Vectorised (no loop)

조회 수: 2 (최근 30일)
Mohammad Ali
Mohammad Ali 2021년 4월 27일
편집: DGM 2021년 4월 28일
How can I sum n terms of
1-1/2+1/3-1/4......

채택된 답변

Khalid Mahmood
Khalid Mahmood 2021년 4월 27일
편집: Khalid Mahmood 2021년 4월 27일
% To reduce 2 more lines
function s=vsum(n)
if nargin<1
s=1; return
end
if mod(n,2)==0, n=n-1;end
s=1+sum(1./[3:2:n] -1./[2:2:n])
  댓글 수: 3
Mohammad Ali
Mohammad Ali 2021년 4월 28일
Khalid's answer is perfect
DGM
DGM 2021년 4월 28일
편집: DGM 2021년 4월 28일
It's perfect if you want the wrong answer 50% of the time.
This is demonstrable. Just test it.
function s=vsum(n)
if nargin<1
s=1; return
end
if mod(n,2)==0, n=n-1;end
s=1+sum(1./[3:2:n] -1./[2:2:n]);
end
Test with odd argument:
s1 = vsum(5)
s2 = 1 - 1/2 + 1/3 - 1/4 + 1/5
results match
s1 =
0.7833
s2 =
0.7833
Test with even argument:
s1 = vsum(4)
s2 = 1 - 1/2 + 1/3 - 1/4
results don't match
s1 =
0.8333
s2 =
0.5833
This whole thing looks like an attempt to make the vector lengths match when they shouldn't.
s2 = sum(1./(1:2:nt))-sum(1./(2:2:nt))
is simpler and actually correct.

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

추가 답변 (2개)

Mohammad Ali
Mohammad Ali 2021년 4월 27일
I hope you may want this.
function s=vsum(n)
if nargin<1
s=1; return
end
if mod(n,2)==0, n=n-1;end
nod=[3:2:n]
nev=[2:2:n]
s=1+sum(1./nod-1./nev)
  댓글 수: 1
DGM
DGM 2021년 4월 27일
This only gives the correct answer for odd inputs.

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


DGM
DGM 2021년 4월 27일
편집: DGM 2021년 4월 27일
You can calculate the sum of a finite alternating harmonic series easy enough:
N = 1000;
n = 1:N;
s = sum((2*mod(n,2)-1)./n)
gives
s =
0.6926

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by