⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jacobi.cpp

📁 并行计算中的Jacobi算法实现
💻 CPP
字号:
// Jacobi
// 2007210764 wangqi

#include "mpi.h"
#include <stdio.h>


#define  TOTAL_SIZE 20
#define  MY_SIZE TOTAL_SIZE/4
#define  PROC_NUM 4

int i, j;
int count, id, processors, length;
int step = 100;

double m1[TOTAL_SIZE][MY_SIZE + 2];
double m2[TOTAL_SIZE][MY_SIZE + 2];
double m3[TOTAL_SIZE];
double m4[TOTAL_SIZE];

char processor_name[MPI_MAX_PROCESSOR_NAME];

int main(int argc, char *argv[])
{
	int start_col, end_col;
	MPI_Status status;

	//Initial status
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &id);
	MPI_Comm_size(MPI_COMM_WORLD, &processors);
	MPI_Get_processor_name(processor_name,&length);
	fprintf(stderr,"\nProcess %d of %d on %s is alive!\n",id,processors,processor_name);


	//Initial matrix
	for (i = 0; i < MY_SIZE + 2; i++)
		for (j = 0; j < TOTAL_SIZE; j++)
			m1[j][i] = 0;

	if (id == 0)
	{
		for (j = 0; j < TOTAL_SIZE; j++ )
			m1[j][1] = 10;
	}
	if (id == PROC_NUM - 1)
	{
		for (j = 0; j < TOTAL_SIZE; j++ )
			m1[j][MY_SIZE] = 10;
	} 
	for (i= 0; i < MY_SIZE + 2; i++ )
	{
		m1[0][i] = 10;
		m1[TOTAL_SIZE - 1][i] = 10;
	}


	//Jacobi
	for (count = 1; count <= step; count++)
	{
		if (id < PROC_NUM - 1)
		{
			MPI_Recv(m3,TOTAL_SIZE, MPI_DOUBLE, (id + 1),10, MPI_COMM_WORLD, &status);
			
			for (j  = 0; j < TOTAL_SIZE; j++)
			{
				m1[j][MY_SIZE + 1] = m3[j];
			}
		}

		if (id > 0)
		{
			for (j  = 0; j < TOTAL_SIZE; j++)
			{
				m4[j] = m1[j][1];
			}
			MPI_Send(m4, TOTAL_SIZE, MPI_DOUBLE, (id - 1),10, MPI_COMM_WORLD);
		}

		if (id < PROC_NUM - 1)
		{

			for (j  = 0; j < TOTAL_SIZE; j++)
			{
				m4[j] = m1[j][MY_SIZE];
			}
			MPI_Send(m4, TOTAL_SIZE, MPI_DOUBLE, (id + 1),10, MPI_COMM_WORLD);
		}

		if (id > 0)
		{
			MPI_Recv(m3, TOTAL_SIZE, MPI_DOUBLE, (id - 1),10, MPI_COMM_WORLD, &status);
			//从接收缓冲区读数据
			for (j  = 0; j < TOTAL_SIZE; j++)
			{
				m1[j][0] = m3[j];
			}

		} 

		start_col = 1;
		end_col = MY_SIZE ;

		if (id == 0)
		{
			start_col = 2;
		}
		if (id == PROC_NUM - 1)
		{
			end_col = MY_SIZE - 1;
		}

		for (i = start_col; i <=end_col; i++)
		{
			for (j = 1; j < TOTAL_SIZE ;j++ )
			{
				m2[j][i] = ( m1[j][i+1] + m1[j][i - 1] + m1[j+1][i] + m1[j-1][i] )/4;
			}
		}

		for (i = start_col; i <=end_col; i++)
		{
			for (j = 1; j < TOTAL_SIZE; j++ )
			{
				m1[j][i]  = m2[j][i];
			}
		} 
	} 
	
	for (j = 1; j < TOTAL_SIZE - 1; j++)
	{
		printf("%d: ", id);
		for (i = start_col; i <= end_col; i++)
		{
			printf("(%f)  ", m1[j][i]);
		}
		printf("\n");
	}   

	MPI_Finalize();

	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -