以下代码在 ray::Task(aggregate_results).Remote(futures); 这一行编不过,如果修改可以编过?
#include <ray/api.h>
#include <iostream>
#include <vector>
#include <cmath>
using namespace ray;
// Map阶段:计算区间[a, b]的积分近似值(使用矩形法)
double calculate_partial_integral(double a, double b, int steps) {
const double dx = (b - a) / steps;
double sum = 0.0;
// 使用中点矩形法提高精度
for(int i = 0; i < steps; ++i) {
double x = a + (i + 0.5) * dx;
sum += 4.0 / (1.0 + x*x);
}
return sum * dx;
}
// Reduce阶段:汇总所有部分结果
double aggregate_results(const std::vector<double>& partial_sums) {
return std::accumulate(partial_sums.begin(), partial_sums.end(), 0.0);
}
// 注册远程函数
RAY_REMOTE(calculate_partial_integral, aggregate_results);
int main() {
ray::Init();
// 积分参数配置
const double a = 0.0; // 积分下限
const double b = 1.0; // 积分上限
const int total_steps = 10000000; // 总分割数
const int num_tasks = 8; // 分布式任务数
// 计算每个任务的分割区间
const double interval = (b - a) / num_tasks;
const int steps_per_task = total_steps / num_tasks;
std::vector<ObjectRef<double>> futures;
// 分发Map任务
for(int i = 0; i < num_tasks; ++i) {
double start = a + i * interval;
double end = start + interval;
auto future = ray::Task(calculate_partial_integral)
.Remote(start, end, steps_per_task);
futures.push_back(future);
}
// 执行Reduce任务
auto result_future = ray::Task(aggregate_results).Remote(futures);
double pi_approx = *result_future.Get();
// 输出结果
std::cout.precision(15);
std::cout << "计算值: " << pi_approx << "\n"
<< "真实π值: " << M_PI << "\n"
<< "绝对误差: " << std::abs(pi_approx - M_PI) << std::endl;
ray::Shutdown();
return 0;
}