How to compute the harmonic series in Python
Harmonic series is an inverse of arithmetic series. So, if
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 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))
Code explanation
In the code snippet above:
Line 2: We declare and define a function
calculate_harmonic_sumwhich takes the numbernas a parameter and returns the sum of harmonic series untiln.Line 3: We declare and assign the variable
total_sumwhich stores the sum of the harmonic series as the series is traversed.Lines 4 – 5: We traverse the harmonic series until
nusing theforloop.Line 6: The
forloop is executed, returning the sum of the harmonic seriestotal_sum.Lines 9 – 10: The
printstatements call the functioncalculate_harmonic_sumand pass7and10as parameters, displaying the sum of their harmonic series.
Free Resources