TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
approximate_pi.cpp
Go to the documentation of this file.
1
19
20
#include <cassert>
21
#include <cstdlib>
22
#include <iostream>
23
#include <vector>
24
29
namespace
math
{
30
35
using
Point
=
struct
{
36
double
x;
37
double
y;
38
};
39
47
double
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
62
static
void
tests
() {
63
std::vector<math::Point> rands;
64
for
(std::size_t i = 0; i < 100000; i++) {
65
math::Point
p;
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
80
int
main
() {
81
tests
();
// run self-test implementations
82
return
0;
83
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
math
for assert
math::Point
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
math::approximate_pi
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
tests
Testcases to check Union of Two Arrays.
math
approximate_pi.cpp
Generated by
1.18.0