sum of series. Vectorised (no loop)
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Mohammad Ali
am 27 Apr. 2021
Bearbeitet: DGM
am 28 Apr. 2021
How can I sum n terms of
1-1/2+1/3-1/4......
0 Kommentare
Akzeptierte Antwort
Khalid Mahmood
am 27 Apr. 2021
Bearbeitet: Khalid Mahmood
am 27 Apr. 2021
% 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 Kommentare
DGM
am 28 Apr. 2021
Bearbeitet: DGM
am 28 Apr. 2021
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.
Weitere Antworten (2)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!