Python program to calculate harmonic series

后端 未结 11 1888
终归单人心
终归单人心 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:16

    @recursive's solution is correct for a floating point approximation. If you prefer, you can get the exact answer in Python 3.0 using the fractions module:

    >>> from fractions import Fraction
    >>> def calc_harmonic(n):
    ...   return sum(Fraction(1, d) for d in range(1, n + 1))
    ...
    >>> calc_harmonic(20) # sum of the first 20 terms
    Fraction(55835135, 15519504)
    

    Note that the number of digits grows quickly so this will require a lot of memory for large n. You could also use a generator to look at the series of partial sums if you wanted to get really fancy.

提交回复
热议问题