In: Computer Science
Using python coding, test for convergence of an infinite sequence or series.
keep the coding at beginner level please!
I wrote up an example function that should work:
Σ (from n=1 to inf) (an )/(bn-1) can be rewritten as Σ (from n=1 to inf) b*(a/b)n . Now that it's in this form, it's clear that this is a geometric series with r=(a/b). Thus, it will converge only when abs(a/b) < 1, and it will diverge otherwise. When it is in the divergent case, we will want to exit the function.
This is the function for it:
def compute_sum(a, b, tolerance=1e-5):
if abs(a/b) >= 1:
return None
n = 1
total_sum = 0
prev_partial = 0
while True:
current_partial = b * (a / b)**n
total_sum += current_partial
if abs(prev_partial - current_partial) < tolerance:
return total_sum
prev_partial = current_partial
n += 1
As you can see, the first thing we do is check for divergence. I
opted to return None
in this case, but you can choose
to throw an error if you'd like.
NOTE:Let me know if this answers your question or if I can explain anything better.