Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
approximate_pi.cpp File Reference

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

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

Classes

struct  math::Point
 

Namespaces

namespace  math
 for std::rand
 

Functions

double math::approximate_pi (const std::vector< Point > &pts)
 
static void test ()
 Self-test implementations. More...
 
int main (int argc, char *argv[])
 Main function. More...
 

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, otherwise 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 ( int  argc,
char *  argv[] 
)

Main function.

Parameters
argccommandline argument count (ignored)
argvcommandline array of arguments (ignored)
Returns
0 on exit
75 {
76 test(); // run self-test implementations
77 return 0;
78}
static void test()
Self-test implementations.
Definition: approximate_pi.cpp:58
Here is the call graph for this function:

◆ test()

static void test ( )
static

Self-test implementations.

Returns
void
58 {
60 for (std::size_t i = 0; i < 100000; i++) {
62 p.x = rand() / (double)RAND_MAX; // 0 <= x <= 1
63 p.y = rand() / (double)RAND_MAX; // 0 <= y <= 1
64 rands.push_back(p);
65 }
66 std::cout << math::approximate_pi(rands) << std::endl; // ~3.14
67}
T endl(T... args)
double approximate_pi(const std::vector< Point > &pts)
Definition: approximate_pi.cpp:35
T push_back(T... args)
T rand(T... args)
Definition: approximate_pi.cpp:30
Here is the call graph for this function: