【MPI高性能计算】梯形面积积分计算

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a19990412/article/details/85320564

简述

S = h [ f ( x 0 ) / 2 + f ( x 1 ) + . . . + f ( x n 1 ) + f ( x n ) / 2 ] S = h * [f(x_0)/2 + f(x_1) + ... + f(x_{n-1}) + f(x_n)/2]

  • 将某个区间分为n段,每段长为h
  • 非常简单的计算公式

MPI实现

#include <mpi.h>
#include <stdio.h>
#include <string>
#include <string.h>
#pragma warning(disable : 4996)
const int MAX_STRING = 100;

#define FUN(x) (x * x)

int main(int argc, char **argv) {
	int comm_sz;
	int my_rank;
	if (argc == 1) return 0;
	
	int n = strtol(argv[1], NULL, 10);
	double a = 0, b = 1;
	MPI_Init(NULL, NULL);
	MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

	int left = n % comm_sz;
	int localn = n / comm_sz + (my_rank < left);
	double h = (b - a) / n, locala, localb;

	if (my_rank < left) { locala = a + my_rank * localn * h; }
	else { locala = a + left * (localn + 1) * h + (my_rank - left) * localn * h; }
	localb = locala + localn * h;

	double x = locala; // initial x
	double localSum = ( FUN(locala) + FUN(localb)) / 2;
	for (int i = 1; i < localn; ++i) {
		x += h;
		localSum += FUN(x);
	}
	localSum *= h;

	if (my_rank != 0) {
		// printf("locala: %f, localb: %f, localSum: %f, i:%d\n", locala, localb, localSum, my_rank);
		MPI_Send(&localSum, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
	}
	else {
		// printf("locala: %f, localb: %f localSum: %f\n", locala, localb, localSum);
		double tempSum = 0;
		for (int i = 1; i < comm_sz; ++i) {
			
			MPI_Recv(&tempSum, 1, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
			localSum += tempSum;
		}
		printf("comm_sz: %d, n: %d, ans: %.5f", comm_sz, n, localSum);
	}
	MPI_Finalize();
}
  • 调用3个线程,分10w个区间算[0,1]区间上的x^2的积分
PS D:\Code\C++\repo\MPITest\x64\Debug> mpiexec -n 3 ./MPITest.exe 100000
comm_sz: 3, n: 100000, ans: 0.33333
PS D:\Code\C++\repo\MPITest\x64\Debug>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/a19990412/article/details/85320564