Python program to calculate harmonic series

后端 未结 11 1913
终归单人心
终归单人心 2020-12-06 19:15

Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...

11条回答
  •  盖世英雄少女心
    2020-12-06 19:31

    I add another solution, this time using recursion, to find the n-th Harmonic number.

    General implementation details

    Function Prototype: harmonic_recursive(n)

    Function Parameters: n - the n-th Harmonic number

    Base case: If n equals 1 return 1.

    Recur step: If not the base case, call harmonic_recursive for the n-1 term and add that result with 1/n. This way we add each time the i-th term of the Harmonic series with the sum of all the previous terms until that point.

    Pseudocode

    (this solution can be implemented easily in other languages too.)

    harmonic_recursive(n):
        if n == 1:
            return 1
        else:
            return 1/n + harmonic_recursive(n-1)
    

    Python code

    def harmonic_recursive(n):
        if n == 1:
            return 1
        else:
            return 1.0/n + harmonic_recursive(n-1)
    

提交回复
热议问题