-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.cpp
More file actions
68 lines (58 loc) · 1.93 KB
/
Copy pathmain.cpp
File metadata and controls
68 lines (58 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <thread>
#include <vector>
double
f(double x)
{
return 4.0 / (1.0 + x * x);
}
int
main(int argc, char* argv[])
{
long long iterations = 1000000;
if (argc > 1) {
iterations = std::atoll(argv[1]);
}
int threads = 10;
if (argc > 2) {
threads = std::atoi(argv[2]);
}
if (iterations <= 0 || threads <= 0) {
std::cerr << "iterations and threads must be positive integers\n";
return 1;
}
const double h = 1.0 / static_cast<double>(iterations);
const long long interior_points = iterations - 1;
const int worker_count = static_cast<int>(std::min<long long>(threads, iterations));
const long long points_per_thread = interior_points / worker_count;
const long long remainder = interior_points % worker_count;
std::vector<std::thread> thread_pool;
thread_pool.reserve(worker_count);
std::vector<double> partial_sums(worker_count, 0.0);
for (int t = 0; t < worker_count; ++t) {
thread_pool.emplace_back([&, t]() {
const long long thread_index = t;
const long long start = 1 + thread_index * points_per_thread + std::min(thread_index, remainder);
const long long end = start + points_per_thread + (thread_index < remainder ? 1 : 0);
double local_sum = 0.0;
for (long long i = start; i < end; ++i) {
const double x = h * static_cast<double>(i);
local_sum += 2.0 * f(x);
}
partial_sums[t] = local_sum;
});
}
for (auto& thread : thread_pool) {
thread.join();
}
// T_n = (h / 2) * (f(0) + f(1) + 2 * sum of interior points).
double sum = f(0.0) + f(1.0);
for (const double partial_sum : partial_sums) {
sum += partial_sum;
}
const double pi = (h / 2.0) * sum;
std::cout.precision(15);
std::cout << "pi = " << pi << '\n';
}