简体   繁体   中英

Sum sequence recursive in Python

I am implementing a recursive code to sum of the sequence: x + x^2 / 2 + x^3 / 3... + x^n / n, i thought a setting combining two recursive functions, but is returning approximate values for n < 4, is very high for n >= 4, obviously is incorrect, but it was the best definition that i thought. Code Below:

def pot(x, n):
    if n == 0: return 1
    else:
        return x * pot(x, n - 1)

def Sum_Seq (x, n): 
    if n == 1: return x 
    else: 
        return x + Sum_Seq(pot(x, n - 1), n - 1) / (n - 1)

If recursion is your mean and not your aim, you can use this function:

def polynom(x,n_max):
    return sum(pow(x,n)*1./n for n in range(1, n_max + 1))

Then you get what you want:

x = 1
for i in range(5):
    print polynom(x,i)
Out:
    0
    1.0
    1.5
    1.83333333333
    2.08333333333

Your Sum_Seq() function should be this:

def Sum_Seq (x, n): 
    if n == 1: 
        return x 
    else: 
        return pot(x, n)*1.0/n + Sum_Seq(x, n-1) # 1.0 is used for getting output as a fractional value.

NOTE: You don't need to make another recursive function calculate power. In python you can just do x**n to get x to the power n.

In fact, I don't see why you need two recursive functions in this case. Simply use x**n to calculate x to the power n :

def sum_seq(x, n):
    if n == 1:
        return x
    else:
        return (x**n/n) + sum_seq(x, n-1)

This works great in Python 3:

>>> power(10, 6)
Out[1]: 189560.0

Keep in mind that, in Python 2, the / operator will infer whether you are doing an integer division or floating-point division. To guarantee your division will be the floating-point division in Python 2, just import the / operator from Python 3 with:

from __future__ import division

or even cast your division to float:

float(x**n)/n

Your pot function seems to perform the job of the ** power operator .

Maybe something like this will help -

In [1]: # x + x^2 / 2 + x^3 / 3... + x^n / n

In [2]: def sum_seq(x, n):
   ...:     if n <= 0:
   ...:         return 0
   ...:     return (x**n)/n + sum_seq(x, n - 1)
   ...:

In [3]: sum_seq(10, 2)
Out[3]: 60.0

EDIT: I think the reason for the erroneous results in your code was this line -

return x + Sum_Seq(pot(x, n - 1), n - 1) / (n - 1)

Adding the Sum_Seq to x, does not follow the pattern you've mentioned

Instead you can use simple linear recursion method

def lin_sum(s,n):

    if n==0:
        return 0
    else:
        return lin_sum(s,n-1)+s[n-1]
s=[1,2,3,4,5]    
print(lin_sum(s,5))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM