MATLAB Answers

Find the sum of the first n

478 views (last 30 days)
bassam792
bassam792 on 15 Feb 2017
Commented: Walter Roberson on 8 Sep 2018
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

Sign in to comment.

Answers (3)

John Chilleri
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!

  6 Comments

Show 3 older comments
John Chilleri
John Chilleri on 15 Feb 2017
Fixed my code - I was using a variable named sum, which can cause errors with an unclear workspace, I apologize.
Marvin Jones
Marvin Jones on 8 Sep 2018
What if you wanted to go in reverse say from n to 1?
Walter Roberson
Walter Roberson on 8 Sep 2018
The theoretical sum would be the same. If you are using floating point then the result could differ. The order of operations of built-in functions like harmonic() is not specified. For doing it yourself, replace 1:n by n:-1:1

Sign in to comment.


Roger Stafford
Roger Stafford on 15 Feb 2017
Or how about this one-liner:
H = det(diag(2:n)+ones(n-1))/factorial(n);

  0 Comments

Sign in to comment.


Walter Roberson
Walter Roberson on 8 Sep 2018
syms x n
symsum(1/x, x, 1, n)

  0 Comments

Sign in to comment.

Tags