Below is an algorithm that uses the Python programming language to calculate the sum of 1 + 1/2 + 1/4 +... + 1 / 2n
.
Import a Python class called Fraction
from the fraction
module.
Then, create a function called sum_of_series
that takes a string as an argument; in this case, the series or the sum of numbers.
Next, split the string into a list and convert all items in the list to float
.
Solve for first_term
and common_ratio
of the series, and then number_of_terms
.
Finally, generate a general formula for the series called result
. This result is equal to the numerator divided by the denominator.
from fractions import Fraction def sum_of_series(string): # splitted the string into a list # replaced the extra spaces with no spaces and # converted all elements in the list into float splitted = string.replace(' ','').split("+") splitted_float = [] for item in splitted: splitted_float.append(float(Fraction(item))) # getting first term using the index of the splitted_float first_term = splitted_float[0] common_ratio =splitted_float[1] / first_term number_of_terms = float(len(splitted_float)) # created a general formula for the series called result. # result is equal to numerator/denominator numerator = first_term * ( 1 - (common_ratio**number_of_terms)) denominator = (1 - common_ratio) result = numerator / denominator return result print((sum_of_series("1 + 1/2 + 1/4 + 1/8 ")))
RELATED TAGS
CONTRIBUTOR
View all Courses