[英]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.我正在实现一个递归代码来求和序列:x + x^2 / 2 + x^3 / 3... + x^n / n,我认为一个组合了两个递归函数的设置,但正在返回近似值n < 4,对于 n >= 4 来说非常高,显然是不正确的,但这是我认为最好的定义。 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:您的Sum_Seq()
函数应该是这样的:
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.在 python 中,你可以只做x**n
来得到 x 的 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
:只需使用x**n
来计算x
的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:这在 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.请记住,在 Python 2 中, /
运算符将推断您是在执行整数除法还是浮点除法。 To guarantee your division will be the floating-point division in Python 2, just import the /
operator from Python 3 with:为了保证你的除法将是 Python 2 中的浮点除法,只需从 Python 3 导入/
运算符:
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 .您的pot
功能似乎执行**
电源操作员的工作。
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将Sum_Seq
添加到 x,不遵循您提到的模式
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.