在Python中的谐波系列

时间:2013-01-22 09:59:17

标签: python math

有没有人知道如何在python中编写Harmonic Series

H(n) = 1 + 1/2 + 1/3 + ... + 1/n

注意:我们不允许从预定义模块导入。输出必须是分数形式(最低项)的答案的分子和分母。

所以这是我的谐波系列的代码。

n = input("Enter n:")  

def harmonic(n):  
    a=1  
    b=1  
    for d in range(2, n+1):  
            a = a*d+b  
            b = b*d  
            return (a,b)  
            x == max(a,b)%min(a, b)  
            if x == 0:  
                y=min(a,b)  
                return y  
            else:  
                y=min(a,b)/x  
                return y  
            a=a/y  
            b=b/y  
            return (a,b)  
print harmonic(n)  

怎么了?无论我输入什么,输出总是(3,2)..出了什么问题? :(请帮助..谢谢:)

5 个答案:

答案 0 :(得分:1)

您可以通过查找数字1..n。

的最小公倍数来找到分母

然后,提名者将是所有值denominator/x的总和,其中x是来自1..n的所有值。

以下是一些代码:

def gcd(a, b):
    """Return greatest common divisor using Euclid's Algorithm."""
    while b:      
        a, b = b, a % b
    return a

def lcm(a, b):
    """Return lowest common multiple."""
    return a * b // gcd(a, b)

def lcmm(args):
    """Return lcm of args."""   
    return reduce(lcm, args)


def harmonic(n):
    lowest_common_multiple = lcmm(range(1,n))
    nominator = sum([lowest_common_multiple/i for i in range(1,n)])
    greatest_common_denominator = gcd(lowest_common_multiple, nominator)
    return nominator/greatest_common_denominator, lowest_common_multiple/greatest_common_denominator

print harmonic(7)
print harmonic(10)
print harmonic(20)

答案 1 :(得分:1)

正如其他人指出的那样,你在d = 2时返回,即(1 + 1/2),它应该在for循环之外。

这是我为此做的一段代码:

#!Python2.7
def gcd(a, b):
    if b: return gcd(b, a%b)
    return a

def lcm(a, b):
    return a*b/gcd(a, b)

def start():
    n = int(raw_input())
    ans = reduce(lambda x, y: (x[0]*lcm(x[1],y[1])/x[1]+y[0]*lcm(x[1],y[1])/y[1], lcm(x[1],y[1])),[(1,x) for x in xrange(1,n+1)])
    _gcd = gcd(ans[0], ans[1])
    print (ans[0]/_gcd, ans[1]/_gcd)

start()

如果您想避免使用reducelamda和列表理解:

#!Python2.7
def gcd(a, b):
    if b: return gcd(b, a%b)
    return a

def lcm(a, b):
    assert a != 0
    assert b != 0
    return a*b/gcd(a, b)

def next(x, y):
    lcmxy = lcm(x[1], y[1])
    return (x[0]*lcmxy/x[1]+y[0]*lcmxy/y[1], lcmxy)

def start():
    n = int(raw_input())
    curr = (1,1)
    for x in xrange(2,n+1):
        curr = next(curr, (1,x))
    _gcd = gcd(curr[0], curr[1]) 
    print (curr[0]/_gcd, curr[1]/_gcd)

start()

答案 2 :(得分:1)

和声系列:

1/1 + 1/2 + ... + 1/n == (n!/1 + n!/2 + ... + n!/n)/n!

因此你可以这样做:

nom = reduce(lambda s, x: s*x, xrange(1, n+1),1)   # n!
denom = sum([nom / x for x in xrange(1, n+1)])

然后你需要在nomdenom上进行gcd-reduction 使用Thorsten Kranz的版本。

请注意,这样只需要拨打gcd一次!

示例:

def gcd(a, b):
    while b:      
        a, b = b, a % b
    return a


def harmonic(n):
    nom = reduce(lambda s, x: s*x, xrange(1,n+1), 1)   # n!
    denom = sum([nom / x for x in xrange(1, n+1)])
    f = gcd(denom, nom)
    return (denom / f), (nom / f)


print harmonic(10)
print harmonic(20)

(7381, 2520)
(55835135, 15519504)

答案 3 :(得分:1)

我必须检查你的尝试两次 - 并插入一个简单的gcd(在原始代码的中间)

n = input("Enter n:")

def harmonic(n): #original harmonic series
     a=1
     b=1
     for d in range(2, n+1):
         a = a*d+b
         b = b*d
     return(a,b)


def harmonic_lt(n): #_lt: harmonic series with lowest terms
                    #not pythonic, but simple
    a=1
    b=1
    for d in range(2, n+1):
        a = a*d+b
        b = b*d

    y=a
    x=b
    while x > 0:
        re = y % x
        y = x
        x = re

    a=a/y
    b=b/y
    return(a,b)

print harmonic(n)
print harmonic_lt(n)

答案 4 :(得分:0)

  

你总是在第一次迭代时返回(a,b)。 - 沙龙“

返回总是结束一个功能。如果返回(a,b),则其余代码无法访问