Harmonic series is an inverse of arithmetic series. So, if
Let's take a look at an 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 sumdef calculate_harmonic_sum(n):total_sum = 0.0for i in range(1, n+1):total_sum = total_sum + 1/i;return total_sum;#call calculate_harmonic_sum functionprint("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))
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