意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

MPI Calculating Of Cos

来源:恒创科技 编辑:恒创科技编辑部
2024-02-03 08:32:59



MPI Calculating Of Cos_#include


MPI Calculating Of Cos


MPI Calculating Of Cos_i++_02

给定极限的上限和下限,计算cos的积分值;

将积分区域,平均分发给每个进程,每个进程计算其中的一区域,最后将所得结果发送给根进程;

其中p表示进程的个数;

n表示划分的每个积分区域,其中的小矩形的的个数;

h表示每个小矩形的宽度;

每次所取的x的值为,当前小矩形的中点值;

#include <stdio.h>
#include <mpi.h>
#include <malloc.h>
#include <math.h>


int main(int argc, char** argv){
int size, rank, i, n = 10000, j;
//int ans;
double a, h, limit[2];
double *local_cos, each_cos, root_cos;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(comm, &size);
MPI_Comm_rank(comm, &rank);
if(rank == 0){
local_cos = (double*)malloc(sizeof(double)*size);
printf("input the lower limit and upper limit:");
scanf("%lf %lf", &limit[0], &limit[1]);//积分的上下限
}
MPI_Bcast(limit, 2, MPI_DOUBLE, 0, MPI_COMM_WORLD);
each_cos = 0.0;//每个进程最后的计算结果
h = (limit[1] - limit[0])/size/n;//每个小矩形的宽度
for(j = 0; j < n; j++){
a = limit[0] + (rank*n + j)*h;
each_cos += cos(a + h/2)*h;
}//计算所分配区域的积分值
printf("Process %d cos(x):%lf\n", rank, each_cos);
MPI_Gather(&each_cos, 1, MPI_DOUBLE, local_cos, 1, MPI_DOUBLE, 0, comm);
if(rank == 0){
//for(i = 1; i < size; i++)
// MPI_Recv(&local_cos[i], 1, MPI_DOUBLE, i, 99, comm, &status);
root_cos = local_cos[0];
for(i = 1; i < size; i++){
root_cos += local_cos[i];//对最后的结果进行累加
}
//ans = root_cos;
printf("the cos(x) is:%lf\n", root_cos);
}
//else{
//MPI_Send(&each_cos, 1, MPI_DOUBLE, 0, 99, comm);
//}
MPI_Finalize();
return 0;
}

上一篇: SPIN Routing Algorithm 下一篇: 手机怎么远程登录云服务器?