Skip to content

Instantly share code, notes, and snippets.

@lazarljubenovic
Created June 17, 2017 10:07
Show Gist options
  • Save lazarljubenovic/2b4f652a42741d87d279c0c68b6d95ed to your computer and use it in GitHub Desktop.
Save lazarljubenovic/2b4f652a42741d87d279c0c68b6d95ed to your computer and use it in GitHub Desktop.
#include <mpi.h>
#include <stdio.h>
#define W MPI_COMM_WORLD
#define n 99999
void printArray(int size, double array[size], int rank) {
for (int i = 0; i < size; i++) {
if (rank == -1) printf("%4.4f ", array[i]);
else printf("{%d}%4.4f ", rank, array[i]);
}
printf("\n");
}
double f(double x) {
return 4.0 / (1.0 + x * x);
}
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(W, &rank);
MPI_Comm_size(W, &size);
double step = 1.0 / n;
double x[n], localX[n / size];
double locSolution = 0, solution;
if (rank == 0) {
double curr = 0;
for (int i = 0; i < n; x[i++] = curr += step);
}
// Svako dobije jednake odsecke da sracuna delove integrala
MPI_Scatter(x, n / size, MPI_DOUBLE, localX, n / size, MPI_DOUBLE, 0, W);
// Racunamo delove integrala
for (int i = 0; i < n / size; locSolution += f(localX[i++]) * step);
// Saberemo sve delove
MPI_Reduce(&locSolution, &solution, 1, MPI_DOUBLE, MPI_SUM, 0, W);
if (rank == 0) printf("%.25f\n", solution);
MPI_Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment