Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <math.h>
- #include <mpi.h>
- #include "l17.h"
- #define CIRCLE(step, i) sqrt(4.0 - (double) (i) * (step) * (double) (i) * (step))
- int main(int argc, char** argv) {
- int rc;
- rc = MPI_Init(&argc, &argv);
- L17_CHECK_ERROR(MPI_Init, rc);
- int size;
- rc = MPI_Comm_size(MPI_COMM_WORLD, &size);
- L17_CHECK_ERROR(MPI_Comm_size, rc);
- int rank;
- rc = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
- L17_CHECK_ERROR(MPI_Comm_rank, rc);
- if (rank == 0) {
- int N;
- FILE* datp = fopen("mar11-pi2.dat", "r");
- if (datp == NULL) {
- printf("Error. Can't open the data file.\n");
- MPI_Abort(MPI_COMM_WORLD, 1);
- }
- rc = fscanf(datp, "%d", &N);
- if (rc != 1) {
- printf("Error. Can't read the N from the data file.\n");
- MPI_Abort(MPI_COMM_WORLD, 2);
- }
- fclose(datp);
- int i;
- for (i = 1; i < size; ++i) {
- rc = MPI_Send(&N, 1, MPI_INT, i, 1, MPI_COMM_WORLD);
- L17_CHECK_ERROR(MPI_Send, rc);
- }
- double step = 2.0 / (double) N;
- double S_no_coef, FS_no_coef = 0;
- int k = size - 1;
- int j;
- for (j = 0; j < k; ++j) {
- rc = MPI_Recv(&S_no_coef, 1, MPI_DOUBLE, j + 1, 1, MPI_COMM_WORLD, NULL);
- L17_CHECK_ERROR(MPI_Recv, rc);
- FS_no_coef += S_no_coef;
- }
- double coef = step / 2.0;
- double FS = FS_no_coef * coef;
- printf("Pi = %f\n", FS);
- }
- else {
- int j = rank - 1, k = size - 1, ibeg, iend;
- int N;
- rc = MPI_Recv(&N, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, NULL);
- L17_CHECK_ERROR(MPI_Recv, rc);
- ibeg = (N / k) * j;
- iend = (j == k - 1) ? (N - 1) : ((N / k) * (j + 1) - 1);
- double step = 2.0 / (double) N;
- double f_old = CIRCLE(step, ibeg);
- double f_new;
- double S_no_coef = 0;
- int i;
- for (i = ibeg; i <= iend; ++i) {
- f_new = CIRCLE(step, i + 1);
- S_no_coef += f_old;
- S_no_coef += f_new;
- f_old = f_new;
- }
- rc = MPI_Send(&S_no_coef, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD);
- L17_CHECK_ERROR(MPI_Send, rc);
- }
- MPI_Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment