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.

1 2 |
import math print(math.pi) |

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.

1 2 3 4 5 6 |
def leibniz(n): pi = 0 for i in range(n): pi += ((4.0 * (-1)**i) / (2*i + 1)) return pi print(leibniz(1000000)) |

### 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.

1 2 3 4 5 6 7 8 9 10 |
import random def monte_carlo(n): inside = 0 for _ in range(n): x, y = random.random(), random.random() if x<strong>2 + y</strong>2 <= 1: inside += 1 return (inside / n) * 4 print(monte_carlo(10000000)) |

The full Python code for this tutorial:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import math import random print('Using math module:', math.pi) def leibniz(n): pi = 0 for i in range(n): pi += ((4.0 * (-1)**i) / (2*i + 1)) return pi print('Using Leibniz series:', leibniz(1000000)) def monte_carlo(n): inside = 0 for _ in range(n): x, y = random.random(), random.random() if x**2 + y**2 <= 1: inside += 1 return (inside / n) * 4 print('Using Monte Carlo Method:', monte_carlo(10000000)) |

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.