MPI Calculating Of Cos

                                                                             

                                      

 给定极限的上限和下限,计算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; 
} 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值