How to Approximate Pi in Python

In this tutorial, we are going to learn how to approximate the mathematical constant Pi in Python. Pi is an irrational number that is the ratio of a circle’s circumference to its diameter, often approximated as 3.14.

Despite its simplicity, finding an accurate value of Pi is a challenging task even for modern supercomputers. However, approximating Pi can be done through several methods which we’ll be discussing and coding in Python.

Step 1: Using Python’s math Module

One simple way of getting the value of Pi in Python is by importing the math module.

The output will be:

3.141592653589793

Step 2: The Gregory-Leibniz Series

The Gregory-Leibniz series is an infinite series summation formula for π. It converges slowly, meaning a large number of terms are needed to obtain a good approximation.

Step 3: The Monte Carlo Method

It is a random sampling technique often used in numerical computing. The idea is to take random points inside a square, and then determine how many of those points fall inside a quarter circle.

The full Python code for this tutorial:

Using math module: 3.141592653589793
Using Leibniz series: 3.1415916535897743
Using Monte Carlo Method: 3.1411584

Conclusion

In this tutorial, we learned how to approximate Pi in Python using various methods such as Python’s built-in math module, the Gregory-Leibniz series, and the Monte Carlo method.

Grab the full code listed above and see how each method approximates the Pi value. You are able to adjust the degree of approximation to be as precise as you need, remembering that there is a trade-off between computational resources and precision.