Home/Blog/Programming/Estimating the value of pi using random numbers
Home/Blog/Programming/Estimating the value of pi using random numbers

Estimating the value of pi using random numbers

7 min read
Feb 14, 2024
content
Motivation
Inscribing the circle in a square
The area of the circle and the square
Setting up a dartboard
Randomized experiment
Applying Pythagoras’ theorem
Conclusion

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Motivation#

Pi (π\pi) is a mathematical constant used in different applications in mathematics and physics. One of its common applications is that it represents the ratio of the circumference of a circle to its diameter as shown in the following equation:

C=2πr\begin{equation} C = 2 \pi r \end{equation}

Here CC is the circumference and rr is the radius of the circle. It is approximated as 3.143.14. π\pi is an irrational number. It means that it can’t be expressed in the form pq\frac{p}{q} where pp and qq are integers and q0q \neq 0. The commonly used interpretation of π\pi (227\frac{22}{7}) is also an approximation.

In this blog, we’ll learn how to estimate the value of π\pi using random numbers.

Let’s start with drawing a circle of radius r=1r=1 around the origin (0,0)(0,0) as shown below.

Circle of radius r
Circle of radius r

Inscribing the circle in a square#

Let’s place the circle in a square whose one side has the same length as that of the diameter of the circle.

The following illustration shows the circle inscribed in a square.

A square drawn outside the circle
A square drawn outside the circle

Guess what would be the length of each side of the square? As the length of each side is 2r2r and r=1r=1, therefore the length of each side is 22.

The area of the circle and the square#

Let’s compute the area of both shapes: the circle as well as the square. The area of the circle is πr2\pi r^2. As r=1r=1 in this setting, so, the area of this circle is π\pi. The area of a square is computed as the square of the length of its side. The length of one side of the square is 2r2r and r=1r=1. Therefore, the length of one side is 22, and the area of the square is 22=42^2 = 4.

Setting up a dartboard#

Assume that the square is the total surface area available to us and we hang a circular dartboard on this area. The geometric properties of the available area and the dartboard are the same as those of our drawn shapes. We want to throw a dart and hit the circle. There are two possibilities:

  • We hit the circle successfully.
  • We miss the circle and the dart hits the outer square. Remember that is the total area available to us.

The probability of hitting the circle is the ratio of the area of the circle and that of the square. Let’s call it PP.

P=π4\begin{equation}P = \frac{\pi}{4}\end{equation}

Dartboard
Dartboard

Randomized experiment#

Now, let’s model and conduct an empirical experiment to throw the darts and examine whether they hit the circle or miss it. Each point hit by a dart is defined as (x,y)(x, y). The exact values of xx and yy are random as they are being determined by the physical experiment. We need to generate two random numbers notating xx and yy. For this purpose, we use the rand() function of C++. It generates a positive random integer. If we reanalyze our surface area, both of its coordinates are bound between 1-1 and 11. Our randomly generated number should be a real number between 1-1 and 11.

  • First of all, we limit the upper bound of the random number by dividing it over RAND_MAX which represents a significantly large integer (greater than or equal to the random integer).
  • We multiply the random integer by 1.01.0 before dividing it over RAND_MAX so that we get a real number as the output. This confines the random number between 00 and 11 (both inclusive).
  • Next, we multiply it by 22 to double the possible range between 00 and 22.
  • At the end, we add 1-1 into it to shift its range between 1-1 and 11 (both inclusive).

We perform the experiment twice for xx and yy coordinates.

Applying Pythagoras’ theorem#

Let’s understand how we can characterize a randomly generated point (x,y)(x, y) geometrically. Pythagoras’ theorem states that the hypotenuse can be computed using the other two sides in a right-angled triangle. A right-angled triangle that has a hypotenuse equal to the radius of the circle (r)(r) is shown in the following figure. We drop a perpendicular to get the projection on the x-axis. The perpendicular height gives the height (y)(y) and the projection length gives the base (x)(x) of the right-angled triangle.

Relationship of r with x and y
Relationship of r with x and y

According to Pythagoras’ theorem:

r2=x2+y2\begin{equation}r^2=x^2+y^2\end{equation}

The circle has r=1r=1. So, r2=1r^2=1. The above equation becomes:

1=x2+y2\begin{equation}1=x^2+y^2\end{equation}

If our randomly generated point (x,y)(x,y) falls exactly at the boundary of the circle, then x2+y2=1x^2+y^2 = 1. If it falls within the circle then x2+y2<1x^2+y^2 < 1. And if it falls outside the circle then x2+y2>1x^2+y^2 > 1.

Let’s treat the outer square as a wall where we have hung a circular dartboard at its center. The radius of the circle is 11. If we throw a dart then it would either hit the circle or miss it. If the dart hits the circle then x2+y21x^2+y^2\leq1. If it misses the circle then it hits the part of the square that’s not covered by the circle. If we perform a physical experiment repeatedly—say 100,000 times and call it trials\text{trials}— we can count how many times the dart hits—let’s call it hits\text{hits}—the circle. Based on this empirical exercise, we can estimate the probability of hitting the circle as follows:

P=hitstrials\begin{equation}P=\frac{\text{hits}}{\text{trials}}\end{equation}

Recall we computed PP using the geometric properties too. We can equate equations (2)(2) and (5)(5) as follows:

π4=hitstrials\begin{equation}\frac{\pi}{4}=\frac{\text{hits}}{\text{trials}}\end{equation}

π=4×hitstrials\begin{equation}\pi=4 \times \frac{\text{hits}}{\text{trials}}\end{equation}

In the following program, we simulate the same experiment. We generate (x,y)(x,y) 100,000 times, count Hits\text{Hits}, and estimate π\pi.

#include <iostream>
using namespace std;
int main()
{
srand(time(0));
double trials = 100000;
double hits = 0;
for (int i = 0;i<=trials;i++)
{
double x = -1 + 2 * (rand()*1.0)/RAND_MAX;
double y = -1 + 2 * (rand()*1.0)/RAND_MAX;
if (x*x+y*y<=1)
hits++;
}
double pi = hits/trials*4;
cout<<"Estimated value of pi = "<<pi;
return 0;
}

Let’s go through the code:

  • Lines 6–7: We initialize the number of trials as 100000 in trials and the number of hits as zero in hits. We set their data type to double so that we may preserve the calculations in the real domain later.
  • Line 8: We configure the loop counter to run the trials iterations.
  • Lines 10–11: We generate two random numbers between 1-1 and 11.
  • Lines 12–13: We characterize the generated random point (x,y)(x, y) to check if it falls within the circle or not. If it falls within the circle then we increment hits. Otherwise we treat it as a missed shot and the next iteration follows.
  • Line 15: Finally, we estimate the value of pi based on the randomized experiment and geometric characteristics of the circle and square.

Run this program multiple times and you will see a fluctuation in the estimated value of pi each time you run it. This fluctuation will remain there because our estimation is based on the randomized experiment.

Conclusion#

In this blog, we used a dartboard inscribed in a square to estimate the value of π\pi. We used geometric characteristics and empirical experiments to estimate the probability of hitting the dartboard when a dart is thrown. Equating the probability computed using these two methods led us to estimate the value of π\pi.

Consider exploring some of the programming-intensive courses at Educative:

Learn to Code: C++ for Absolute Beginners

Cover
Learn C++

C++ is a versatile language known for its efficiency and flexibility, widely used in industries like game development, finance, and system programming. This course dives deep into C++ programming foundations, focusing on practical problem-solving techniques. You will start by learning basic problem-solving skills using simple programs and execution sheets. Then, you'll explore decision-making, branching, loops, and manipulation of strings and arrays using C++ programming. Finally, the course will cover functions and complex program structures, ensuring a comprehensive grasp of the language's capabilities. By the end, you will be equipped with problem-solving skills, a solid understanding of C++ basics, and confidence in writing structured code, setting you on the path to becoming a proficient C++ developer.

8hrs
Beginner
4 Challenges
4 Quizzes

Competitive Programming in C++: The Keys to Success

Cover
Competitive Programming in C++: The Keys to Success

Competitive programming can be a great way to build out your programming skills, get on any major company’s radar, and earn a little extra cash along the way. In this course, you will learn to prepare for competitive programming contests like ACM ICPC, Google CodeJam, Facebook HackerCup, and many more. Each topic is broken down with a healthy mix of theory, code samples, step-by-step solved sample problems, illustrations, useful practice problems, and tips and tricks for faster implementation. You will need some solid C++ foundations coming into this course, but by the end it, you will be confident enough in your C++ skills to take home the win.

5hrs
Beginner
40 Playgrounds
255 Illustrations

Learn C++: The Complete Course for Beginners

Cover
Learn C++: The Complete Course for Beginners

If you're a beginner and want to learn C++ to start your coding journey, you're in the right place. This comprehensive course starts from the absolute basics and gradually builds up to exciting real-life coding projects. The emphasis throughout is on practical lessons and analogies that you can relate to. As you learn, you'll work your way through dozens of coding exercises that you can run from right inside your browser. By the time you're done, you'll have a strong grasp of C++, one of the most in-demand programming languages in the world. You'll have gotten plenty of hands-on practice and will be able to confidently write your own applications.

10hrs
Beginner
33 Challenges
67 Quizzes

Written By:
Malik Jahan
Join 2.5 million developers at
Explore the catalog

Free Resources