python 电压 谐波,Python程序来计算谐波序列

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...

解决方案

@Kiv's answer is correct but it is slow for large n if you don't need an infinite precision. It is better to use an asymptotic formula in this case:

0516d4c5d9a19f09ffcfc04a6a596928.png

#!/usr/bin/env python

from math import log

def H(n):

"""Returns an approximate value of n-th harmonic number.

http://en.wikipedia.org/wiki/Harmonic_number

"""

# Euler-Mascheroni constant

gamma = 0.57721566490153286060651209008240243104215933593992

return gamma + log(n) + 0.5/n - 1./(12*n**2) + 1./(120*n**4)

@Kiv's answer for Python 2.6:

from fractions import Fraction

harmonic_number = lambda n: sum(Fraction(1, d) for d in xrange(1, n+1))

Example:

>>> N = 100

>>> h_exact = harmonic_number(N)

>>> h = H(N)

>>> rel_err = (abs(h - h_exact) / h_exact)

>>> print n, "%r" % h, "%.2g" % rel_err

100 5.1873775176396242 6.8e-16

At N = 100 relative error is less then 1e-15.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值