Python program to calculate harmonic series

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

    A fast, accurate, smooth, complex-valued version of the H function can be calculated using the digamma function as explained here. The Euler-Mascheroni (gamma) constant and the digamma function are available in the numpy and scipy libraries, respectively.

    from numpy import euler_gamma
    from scipy.special import digamma
    
    def digamma_H(s):
        """ If s is complex the result becomes complex. """
        return digamma(s + 1) + euler_gamma
    
    from fractions import Fraction
    
    def Kiv_H(n):
        return sum(Fraction(1, d) for d in xrange(1, n + 1))
    
    def J_F_Sebastian_H(n):
        return euler_gamma + log(n) + 0.5/n - 1./(12*n**2) + 1./(120*n**4)
    
    
    

    Here's a comparison of the three methods for speed and precision (with Kiv_H for reference):

    Kiv_H(x) J_F_Sebastian_H(x) digamma_H(x) x seconds bits seconds bits seconds bits 1 5.06e-05 exact 2.47e-06 8.8 1.16e-05 exact 10 4.45e-04 exact 3.25e-06 29.5 1.17e-05 52.6 100 7.64e-03 exact 3.65e-06 50.4 1.17e-05 exact 1000 7.62e-01 exact 5.92e-06 52.9 1.19e-05 exact

提交回复
热议问题