TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
approximate_pi.cpp File Reference

Implementation to calculate an estimate of the number π (Pi). More...

#include <cassert>
#include <cstdlib>
#include <iostream>
#include <vector>
Include dependency graph for approximate_pi.cpp:

Go to the source code of this file.

Namespaces

namespace  math
 for assert
 

Typedefs

using math::Point
 structure of points containing two numbers, x and y, such that 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1.
 

Functions

double math::approximate_pi (const std::vector< Point > &pts)
 This function uses the points in a given vector 'pts' (drawn at random) to return an approximation of the number π.
 
static void tests ()
 Self-test implementations.
 
int main ()
 Main function.
 

Detailed Description

Implementation to calculate an estimate of the number π (Pi).

We take a random point P with coordinates (x, y) such that 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1. If x² + y² ≤ 1, then the point is inside the quarter disk of radius 1, else the point is outside. We know that the probability of the point being inside the quarter disk is equal to π/4 double approx(vector<Point> &pts) which will use the points pts (drawn at random) to return an estimate of the number π

Note
This implementation is better than naive recursive or iterative approach.
Author
Qannaf AL-SAHMI

Definition in file approximate_pi.cpp.

Function Documentation

◆ main()

int main ( void )

Main function.

Returns
0 on exit

Definition at line 80 of file approximate_pi.cpp.

80 {
81 tests(); // run self-test implementations
82 return 0;
83}
static void tests()
Self-test implementations.

◆ tests()

static void tests ( )
static

Self-test implementations.

Returns
void

Definition at line 62 of file approximate_pi.cpp.

62 {
63 std::vector<math::Point> rands;
64 for (std::size_t i = 0; i < 100000; i++) {
66 p.x = rand() / static_cast<double>(RAND_MAX); // 0 <= x <= 1
67 p.y = rand() / static_cast<double>(RAND_MAX); // 0 <= y <= 1
68 rands.push_back(p);
69 }
70 assert(math::approximate_pi(rands) > 3.135);
71 assert(math::approximate_pi(rands) < 3.145);
72
73 std::cout << "All tests have successfully passed!" << std::endl;
74}
struct { double x; double y;} Point
structure of points containing two numbers, x and y, such that 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1.
double approximate_pi(const std::vector< Point > &pts)
This function uses the points in a given vector 'pts' (drawn at random) to return an approximation of...