How to compute the sum of 1 + 1⁄2 + 1⁄4 + ... + 1/2n
Below is an algorithm that uses the Python programming language to calculate the sum of 1 + 1/2 + 1/4 +... + 1 / 2n.
Methodology
-
Import a Python class called
Fractionfrom thefractionmodule. -
Then, create a function called
sum_of_seriesthat 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_termandcommon_ratioof the series, and thennumber_of_terms. -
Finally, generate a general formula for the series called
result. This result is equal to the numerator divided by the denominator.
Code
from fractions import Fractiondef 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 floatsplitted = string.replace(' ','').split("+")splitted_float = []for item in splitted:splitted_float.append(float(Fraction(item)))# getting first term using the index of the splitted_floatfirst_term = splitted_float[0]common_ratio =splitted_float[1] / first_termnumber_of_terms = float(len(splitted_float))# created a general formula for the series called result.# result is equal to numerator/denominatornumerator = first_term * ( 1 - (common_ratio**number_of_terms))denominator = (1 - common_ratio)result = numerator / denominatorreturn resultprint((sum_of_series("1 + 1/2 + 1/4 + 1/8 ")))