Algorithms_in_C++ 1.0.0
Set of 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:

Namespaces

namespace  math
 for IO operations
 

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

Function Documentation

◆ main()

int main ( void )

Main function.

Returns
0 on exit
80 {
81 tests(); // run self-test implementations
82 return 0;
83}
static void tests()
Self-test implementations.
Definition approximate_pi.cpp:62
Here is the call graph for this function:

◆ tests()

static void tests ( )
static

Self-test implementations.

Returns
void
62 {
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}
T endl(T... args)
struct { double x; double y;} Point
structure of points containing two numbers, x and y, such that 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1.
Definition approximate_pi.cpp:35
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...
Definition approximate_pi.cpp:47
T push_back(T... args)
Here is the call graph for this function: