Calculating Pi using a Python script

Did you know?


Pi (π) is one of the most important and fascinating numbers in mathematics. Roughly 3.14, it is a constant that is used to calculate the circumference of a circle from that circle’s radius or diameter. Pi is also an irrational number, which means that it can be calculated to an infinite number of decimal places without ever slipping into a repeating pattern. This makes it difficult, but not impossible, to calculate precisely.

How to calculate Pi?


Method #1


All we need to calculate Pi is a round object such as a golf ball and a tape measurer.
We will need to take two measurements as follows:

  • Diameter,
  • Circumference

Knowing that Circumference = π x Diameter we can calculate π as follows: π = Circumference / Diameter.
pi-calculation-method-1
As you may have noticed, this method does not give you the exact value of Pi. This due to the fact that the measurements of the diameter and of the circumference of an object are never 100% accurate.

Challenge #1


Your challenge consists of writing a Python script that prompts the end-user to enter both the diameter and the circumference of a round object. Your program should return the corresponding estimation of π by using the formula from method #1: π = Circumference / Diameter.

You can try your algorithm with the following measurements:
pi-calculation-method-1-earth

Method #2: Calculating Pi Using an Infinite Series (Gregory-Leibniz series)


Mathematicians have found several different mathematical series that, if carried out infinitely, will accurately calculate Pi to a great number of decimal places. Some of these are so complex they require supercomputers to process them. One of the simplest, however, is the Gregory-Leibniz series. Though not very efficient, it will get closer and closer to Pi with every iteration, accurately producing Pi to five decimal places with 500,000 iterations. Here is the formula to apply:
pi-calculation-method-2

Challenge #2


Write a Python script that will calculate Pi with at least three accurate decimal places using the Gregory-Leibniz series.
Tip: You will need to use a for loop and decide of a number of iteration for your algorithm.

Method #3: Calculating Pi Using an Infinite Series (Nilakantha series)


The Nilakantha series is another infinite series to calculate Pi that is fairly easy to understand. While somewhat more complicated, it converges on Pi much quicker than the Gregory-Leibniz formula. Here is the formula to apply:
pi-calculation-method-3

Challenge #3


Write a Python script that will calculate Pi with at least three accurate decimal places using the Nilakantha series.

Share Button
Posted in Computer Science, Python - Intermediate, Python Challenges Tagged with: ,

Our Latest Book