Python Program to print Harmonic Series

In this article, we will learn how to print the harmonic series and calculate the sum of the harmonic series in Python. The harmonic series is the inverse of the arithmetic series. The harmonic series is represented by 1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) …. 1/(a + nd). Where

  • a is the starting term.
  • d is a common difference.
  • n is the nth term.

To know more about the harmonic series click here.

Print Harmonic Series

1. Get the user input.

2. Call the harmonic_series with a, d, n as arguments.

3. Then apply the formula (1/a+n*d) to get the nth term of the series.

def harmonic_series(a, d, n):
    for i in range(0, n):
        print(1/(a+i*d))

n = int(input("Enter the number of terms: "))
a = int(input("Enter the starting term: "))
d = int(input("Enter the common difference: "))
print("The first n terms of harmonic series are")
harmonic_series(a, d, n)

Output

Enter the number of terms: 5
Enter the starting term: 1
Enter the common difference: 1
The first n terms of harmonic series are
1.0
0.5
0.3333333333333333
0.25
0.2

Sum of Harmonic Series

1. Declare a variable result to store the sum of the harmonic series.

2. Finally, return the result.

def harmonic_series_sum(a, d, n):
    sum = 0
    for i in range(0, n):
        sum += (1/(a+i*d))

    return sum

n = int(input("Enter the number of terms: "))
a = int(input("Enter the starting term: "))
d = int(input("Enter the common difference: "))
print("The sum harmonic series is ", harmonic_series_sum(a, d, n))

Output

Enter the number of terms: 10
Enter the starting term: 2
Enter the common difference: 1
The sum harmonic series of 1st n terms is 2.019877344877345

Also, refer:

Leave a Reply

Your email address will not be published.