MPI LABS

 

Excercise 1: The trapezoidal rule for numerical integration

 

Numerical function integration is the approximate calculation of the integral of function  f(x)  starting from a point  x=a  upto a final point x=b. As shown in the following figure, the integral is the area of the surface below  f(x)  in the range  a ≤ x ≤ b.

 

The approximation of the integral using trapezoids is donw by partitioning the range [a, b]  into  n  parts of width  h  and adding the areas of the trapezoidal parts as shown below:

 

Integral = ½ h [f(a) + f(a+h)] + ½ h [f(a+h) + f(a+2h)] + ... + ½ h [f(b-h) + f(b)]

            = h/2 [f(a) + f(b)] + h [f(a+h) + f(a+2h) + ... + f(b-h)]

 

Serial Code for implementing the trapeziodal rule

 

/*

 * trapez_ser.c

 *

 *      Author: Kostas Diamantaras

 */

 

#include <stdio.h>

#include <string.h>

#include <math.h>

 

/*

 * The function to be integrated

 */

double f(double x) {

       double y;

       y = 2*exp(-(x-2)*(x-2)/2.0) - exp(-(x-4)*(x-4)) + 0.1*x;

       return y;

}

 

 

int main(int argc, char **argv) {

       /* Integration limits */

       double start, end;

       /* Number of parts */

       int n;

       int i;

       double h, x;

       double integral;

 

       printf("Trapeziodal Integration\n");

       printf("Give starting x --> ");

       fflush(stdout);

       scanf("%lf", &start);

       printf("Give ending x --> ");

       fflush(stdout);

       scanf("%lf", &end);

       printf("Give number of intervals n --> ");

       fflush(stdout);

       scanf("%d", &n);

 

       h = (end-start)/n;

 

       integral = (f(start) + f(end))/2.0;

       for (i = 1; i <= n-1; i++) {

              x = start + h*i;

              integral += f(x);

       }

       integral = integral*h;

 

       /*

        * Print out the result:

        */

       printf("Integral f (with %d trapezoids) = %.6f\n", n, integral);

 

       return(0);

}

 

What you should do

Write a parallel MPI code so the trapezoidal rule is executed by  p  processes. Each process will calculate a partial integral summing up  n/p  parts while process  0  is responsible for collecting the partial integrals in order to calculate and print out the total integral.

 

Exercise 2: Transmitting messages in a ring

 

Using  MPI_Send  and  MPI_Recv  write a parallel program executed by  p  processes and doing the following:

Starting from process  0  transmit a message across a logical ring defined by the processes in the directino shown in the following figure (in this case p=5). The message should return back to process  0.

The message content is the string  “Hello from < s >” where  < s > is the sending process (different each time). Whenever the message is received by some process it will print a message like the following:

Process 3: Received message from 2

Process 4: Received message from 3

etc