蒙特卡洛法并行求解Pi值C++程序
时间: 2023-07-11 08:49:22 浏览: 76
蒙特卡洛法近似求PI值
5星 · 资源好评率100%
以下是并行求解 Pi 值的 C++ 代码,使用蒙特卡洛方法:
```C++
#include <iostream>
#include <random>
#include <thread>
#include <future>
int main() {
const int num_threads = 4; // 线程数
const int num_points = 1000000; // 模拟点数
int num_in_circle = 0; // 圆内点数
std::vector<std::future<int>> futures(num_threads);
std::random_device rd;
std::vector<std::mt19937> gens(num_threads, std::mt19937(rd()));
std::vector<std::uniform_real_distribution<>> dis(num_threads, std::uniform_real_distribution<>(-1.0, 1.0));
for (int i = 0; i < num_threads; ++i) {
futures[i] = std::async(std::launch::async, [&num_points, &num_in_circle, &gens, &dis, i]() {
int local_num_in_circle = 0;
for (int j = 0; j < num_points / num_threads; ++j) {
double x = dis[i](gens[i]);
double y = dis[i](gens[i]);
if (x * x + y * y <= 1) {
++local_num_in_circle;
}
}
return local_num_in_circle;
});
}
for (auto& future : futures) {
num_in_circle += future.get();
}
double pi = 4.0 * num_in_circle / num_points;
std::cout << "Pi = " << pi << std::endl;
return 0;
}
```
该程序使用 `std::async` 函数创建多个异步任务,每个任务在一个独立的线程中运行,模拟在单位正方形内随机投点,判断每个点是否在以原点为圆心、半径为 $1$ 的圆内,最后将每个线程计算得到的圆内点数相加,再根据圆内点数和总点数的比例计算 Pi 值。
阅读全文