All pastes #1486108 Raw Edit

Miscellany

public c v1 · immutable
#1486108 ·published 2009-07-06 21:08 UTC
rendered paste body
#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include <mpi.h>float f(float x);float olokliroma(float,float, float, float);int main(int argc, char *argv[]){	int rank,root = 0,gsize;	int i,j;	int n,myn;	float a,b,h;	float a1,b1,rslt;	float *results;	MPI_Status status;	MPI_Init(&argc, &argv);	MPI_Comm_rank(MPI_COMM_WORLD, &rank);	MPI_Comm_size(MPI_COMM_WORLD, &gsize);	if (rank == root)	{		printf("Dose (float)a: ");scanf("%f",&a);		printf("Dose (float)b: ");scanf("%f",&b);		printf("Dose (int)n: ");scanf("%d",&n);		results = (float*)malloc(n*sizeof(float));	}	MPI_Bcast(&a, 1, MPI_FLOAT, root, MPI_COMM_WORLD);	MPI_Bcast(&b, 1, MPI_FLOAT, root, MPI_COMM_WORLD);	MPI_Bcast(&n, 1, MPI_INT, root, MPI_COMM_WORLD);	/*tha kanei n/gsize epanalipseis (+1 an den einai akrives to n/g kai 	  anikei se rank pou "xoraei" na parei epipleon */	for (i = 0; i < ((n/gsize) + (int)((n%gsize) > rank)) ; i++)	{		myn = i*gsize + rank; /*Exoume poio komati antistoixei sto proc */		a1 = (b-a)/n * myn;		b1 = ((b-a)/n * (myn+1));		h = (b1 - a1)/n;		rslt = olokliroma(h,a1,b1,n);		if (rank != root) /* o root den xreiazete na stilei */			MPI_Send(&rslt, 1, MPI_FLOAT, root, 5,MPI_COMM_WORLD);		else /*alla sozei tin timi stin sosti thesi */			memcpy(results+myn, &rslt,sizeof(float));	}	if (rank == root)	{		rslt = 0.; /*tha xrisimopoiithei san summary */		for (i = 0; i < n; i++)		{			if (i%gsize != root ) /*den kanei recieve ap ton eafto tou */				MPI_Recv(results+i,1,MPI_FLOAT,i%gsize,5, MPI_COMM_WORLD, &status);			printf("Recieved from %d : %f\n", i%gsize, results[i]);			rslt += results[i];		}		printf("Teliko apotelesma %f\n", rslt);	}			MPI_Finalize();	return EXIT_SUCCESS;}float f(float x){	return (5*(x*x) + 3*x + 2);}float olokliroma(float h,float a, float b, float n){	int i;	float summ = 0;	for (i = 1; i < n; i++)		summ += f(a+i*h);	return (h*(f(a)/2 + f((a+n*h))/2  + summ));}