Reputation: 43
I'm new to python and I'm trying to model the convergence of a series towards pi based on a defined term. I've managed to create a list that returns the approximate value for pi at each iteration, however, I'm struggling to create a list that returns the difference between the approximation for pi and math.pi. I understand that the code is currently just looping the error term for one value of pi, and I don't know how to loop it over n values of pi. I'm sure it's a simple fix that I'm just overlooking so any help would be greatly appreciated. Here's my code:
from math import pi
from math import factorial
def term_in_series_1(n):
values=[]
for k in range (n, -1,-1): #Here we are creating a for loop starting at n, finishing at -1 with a stepsize of -1
value_of_term_n = 2 * 2**k * (factorial(k))**2 / factorial(2*k+1) #The loop uses this equation to calculate the value term of n for values in the range of n
values.append(value_of_term_n) #The append function allows each new value term of n to be added to the empty list "values" with length n
return values
def series_1(n):
approximation_for_pi = sum(term_in_series_1(n)) #This line is taking the sum of all the values in the series calulated in the previous function
return approximation_for_pi
def error_1(j):
values=[]
for i in range (j):
for k in range (n):
value_of_error_1 = pi - series_1(n) #The loop uses this equation to calculate the value term of n for values in the range of n
values.append(value_of_error_1) #The append function allows each new value term of n to be added to the empty list "values" with length n
return values
error_1(15)
Upvotes: 0
Views: 64
Reputation: 41872
This code seems to be the problem:
for i in range (j):
value_of_error_1 = pi - series_1(n)
You have an iteration variable i
but refer to n
out of nowhere. Assuming the iteration variable should be n
, here's a rework of your code:
from math import pi, factorial
def term_in_series_1(n):
values = []
for k in range(n, -1, -1):
value_of_term_n = 2 * 2**k * factorial(k)**2 / factorial(2*k+1)
values.append(value_of_term_n)
return values
def series_1(n):
return sum(term_in_series_1(n))
def error_1(j):
errors = []
for n in range(j):
errors.append(pi - series_1(n))
return errors
print(error_1(10))
Upvotes: 1