# Geometric Series with Python

#### Background Story :

There were a couple of mathematicians went to a bar, the first guy ordered one beer, the second guy asked for 1/2 of a beer, the third guy asked for 1/4 of a beer, the fourth ordered 1/8 of a beer, and so on… The hot bartender rolled her eyes, poured two beers, and says, “Here, you guys work it out ! 😍

#### Question: What is the Summation of

1 +1/2+ 1/4 +1/8 +1/16 ...

RitaE / Pixabay

#### Solution:

This is a famous example of a Geometric series

The fundamental idea is the base on the formula:

a^2 - b^2= (a-b)(a+b)

1-x^n= (1-x)(1+x+x^2 +x^3 +x^4....x^n-1)

For infinity series we have :

So the General Formula would be:

Then we have the result to be 1+ 1 =2 Beers :

Now we can check if Python does a good job with computing the Series.

def SumofGeo(a,r,n):
sum=0
i=0
while i <n:
sum=sum+a
a=a*r
i=i+1
return sum

SumofGeo(1,1/2,5)
SumofGeo(1,1/2,10)
SumofGeo(1,1/2,100)

Python Output:

Out[6]: 1.9375

Out[7]: 1.998046875

Out[8]: 2.0

As we can see when n=5, the geometric sum of (1/2)^n is 1.93, when n=10, the sum is 1.99. when n=100, python assumed it is 2. Remember theoretically, it is not 2 yet, the sum is 2 when n approaches infinity!

So the Hot BarTender is smart!!

References: