Recursive sequence sum
I am implementing a recursive code that sums the following sequence: x + x^2 / 2 + x^3 / 3... x^n / n, for this sum, I thought of a definition, combining two recursive functions, as follows low, but it is returning very high values, for n > 3.
def potencia(x, n):
if n == 0: return 1
else:
return x * potencia(x, n - 1)
def Soma_Seq (x, n):
if n == 0: return 0
else:
return x + Soma_Seq(potencia(x, n - 1), n - 1) / n
0
Author: Marcelo de Sousa, 2017-08-19
2 answers
Given: Soma(x,n) = x + x^2 / 2 + x^3 / 3 + ... + x^n / n
Notice that:
Soma(x,n) = x + x^2 / 2 + x^3 / 3 + ... + x^n / n
# |----------------------------|
Soma(x,n) = Soma(x,n-1) + x^n / n
Defining that, for n=1
: Soma(x, 1) = x
def potencia(x, n):
return (x**n)
def Soma_Seq (x, n):
if n == 1: return x
else:
return Soma_Seq(x, n-1) + potencia(x, n)/n
We can also write the function potencia()
recursively as follows:
def potencia(x, n):
if n == 1: return x
else:
return x * potencia(x, n-1)
1
Author: AlexCiuffa, 2019-03-27 16:55:54
We can use this answer for your question:
Recursive function that simulates a high number at a Power
def potencia(base, power, show_steps=True):
"""show_steps serve só para dizer
se amostrar os passos recursivos escritos ou não."""
if power == 0: # caso base
if show_steps:
print(base, "^{0} = 1", sep="")
return 1
else: # passo recursivo
if show_steps:
print(base, "^{", power, "} = ", base, " * ", base, "^{", power - 1, "}", sep="")
return base * potencia(base, power - 1, show_steps)
def Soma_Seq (x, n):
if n == 0: return 0
else:
return x + Soma_Seq(potencia(x, n - 1), n - 1) / n
I think it's a good starting point.
0
Author: Dorathoto, 2017-08-22 14:22:43