TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
approximate_pi.cpp
Go to the documentation of this file.
1
20#include <cassert>
21#include <cstdlib>
22#include <iostream>
23#include <vector>
24
29namespace math {
30
35using Point = struct {
36 double x;
37 double y;
38};
39
47double approximate_pi(const std::vector<Point> &pts) {
48 double count = 0; // Points in circle
49 for (Point p : pts) {
50 if ((p.x * p.x) + (p.y * p.y) <= 1) {
51 count++;
52 }
53 }
54 return 4.0 * count / static_cast<double>(pts.size());
55}
56} // namespace math
57
62static void tests() {
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}
75
80int main() {
81 tests(); // run self-test implementations
82 return 0;
83}
static void tests()
Self-test implementations.
int main()
Main function.
for assert
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...