How to Calculate the Value of Pi in Python


In this example we will show how to calculate the value of pi (π) using a Monte Carlo method in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# computePi.py
# Calculate the value of pi by using Monte Carlo method in Python 

import random 
import math

def main():
    print('Please input loop number:')
    n = int(input())            # n is the number of random points  
    total = 0                       # total is the number of random points inside the circle 

    for i in range(n):
        x = random.random()
        y = random.random()
        
        if math.sqrt(x**2 + y**2) < 1.0:   # judge whether the point is inside the circle
            total += 1
    
    piResult = 4.0 * total / n                   # obtain the value of Pi

    print('After ', n, ' loops, calculated value of Pi:', piResult)
    print('Actual value of Pi:', math.pi)
    print('The error:', abs(math.pi - piResult) / math.pi)

if __name__ == '__main__':
    main()

After running the codes above, we can get these results:

1) The number of iterations is set to 100.

2) The number of iterations is set to 1000.

3) The number of iterations is set to 10000.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments