# Algorithms_in_C++: math/approximate_pi.cpp File Reference

Loading...
Searching...
No Matches
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

  argc | commandline argument count (ignored)
  argv | commandline array of arguments (ignored)

Returns
  0 on exit

{
test(); // run self-test implementations
return 0;
}
test
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

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