Find the sum of the first n
439 views (last 30 days)
Show older comments
Find the sum of the first n terms of the harmonic series where n is an integer greater than one 1+1/2+1/3+1/4+1/5+.....
0 Comments
Answers (3)
John Chilleri
on 15 Feb 2017
Edited: John Chilleri
on 15 Feb 2017
Hello,
This can be done simply with,
n = 100; % whatever you want
sum_harm = 0;
for i = 1:n
sum_harm = sum_harm + 1/i;
end
or even,
n = 100; % whatever you want
sum_harm = sum(1./(1:n));
Hope this helps!
7 Comments
Walter Roberson
on 4 Jun 2021
format long g
n = 1e10; % whatever you want
sum_harm_forward = 0;
sum_harm_reverse = 0;
for i = 1:n
sum_harm_forward = sum_harm_forward + 1/i;
sum_harm_reverse = sum_harm_reverse + 1/(n - i + 1);
end
sum_harm_forward
sum_harm_reverse
sum_harm_forward - sum_harm_reverse
Roger Stafford
on 15 Feb 2017
Or how about this one-liner:
H = det(diag(2:n)+ones(n-1))/factorial(n);
2 Comments
Walter Roberson
on 8 Sep 2018
syms x n
symsum(1/x, x, 1, n)
1 Comment
Hesbon Osoro
on 3 Jun 2021
Very much useful to test the convergence of a harmonic series without lagging a machine, so fast code also. It is of great help.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!