SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
5.recursion
Exercise:
Programming Excercises
Question:4 | ISBN:978013274719 | Edition: 6

Question

(Sum series) Write a recursive function to compute the following series:

                          m(i) = 1+ 1/2 + 1/3 +.........+1/i
Write a test program that displays m(i) for i 1, 2, ..., 10.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Sum Series Python code:

#'computeSeries' is used to compute the 
#series m(i) = 1 + 1/2 + 1/3 + ... + 1/i.
def computeSeries(i):
    # Base case: If i is 1, return
    # the base value of the series.
    if i == 1:
        return 1.0
    
    # Recursive case: Compute the sum of the
    #series up to i-1 and add 1/i.
    return computeSeries(i - 1) + 1.0 / i
# Test program to display m(i) for i = 1 to 10.
for i in range(1, 11):
    result = computeSeries(i)
    print(f"m({i}) = {result:.4f}")

Executed Output:

m(9) = 2.8290
m(10) = 2.9290

 

0 0

Discussions

Post the discussion to improve the above solution.