How to compute the harmonic series in Python

Harmonic series is an inverse of arithmetic series. So, if 1/a,1/(a+d),1/(a+2d),1/(a+3d).1/(a+nd)1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) …. 1/(a + nd) are in harmonic series then a,a+d,a+2d,a+3da+nda, a+d, a+2d, a+3d … a+nd will be an arithmetic series

Let's take a look at an example.

Example

Here, we will calculate the sum of the first n numbers in the harmonic series. The sum of the harmonic series will be in the form of:

It can be computed in code as follows:

#function to calculate harmonic series sum
def calculate_harmonic_sum(n):
total_sum = 0.0
for i in range(1, n+1):
total_sum = total_sum + 1/i;
return total_sum;
#call calculate_harmonic_sum function
print("Sum of first 7 numbers in harmonic series : ", round(calculate_harmonic_sum(7), 5))
print("Sum of first 10 numbers in harmonic series : ", round(calculate_harmonic_sum(10), 5))

Code explanation

In the code snippet above:

  • Line 2: We declare and define a function calculate_harmonic_sum which takes the number n as a parameter and returns the sum of harmonic series until n.

  • Line 3: We declare and assign the variable total_sum which stores the sum of the harmonic series as the series is traversed.

  • Lines 4 – 5: We traverse the harmonic series until n using the for loop.

  • Line 6: The for loop is executed, returning the sum of the harmonic series total_sum.

  • Lines 9 – 10: The print statements call the function calculate_harmonic_sum and pass 7 and 10 as parameters, displaying the sum of their harmonic series.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved