fork download
  1. #include "mpi.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5.  
  6. #define MASTER 0
  7. #define POLY_DEGREE 3
  8. #define X_VALUE 2.0
  9.  
  10. int main(int argc, char* argv[]) {
  11. int numtasks, taskid;
  12. float global_result = 0.0, local_result = 0.0;
  13. float coefficients[POLY_DEGREE + 1];
  14.  
  15. MPI_Init(&argc, &argv);
  16. MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
  17. MPI_Comm_rank(MPI_COMM_WORLD, &taskid);
  18.  
  19. if (taskid == MASTER) {
  20. for (int i = 0; i <= POLY_DEGREE; i++) {
  21. coefficients[i] = i + 1.0;
  22. }
  23. printf("Polinomul: ");
  24. for (int i = POLY_DEGREE; i >= 0; i--) {
  25. printf("%.2fx^%d ", coefficients[i], i);
  26. if (i != 0) {
  27. printf("+ ");
  28. }
  29. else {
  30. printf("\n");
  31. }
  32. }
  33. }
  34.  
  35. MPI_Bcast(coefficients, POLY_DEGREE + 1, MPI_FLOAT, MASTER, MPI_COMM_WORLD);
  36.  
  37. int chunk_size = (POLY_DEGREE + 1) / numtasks;
  38. int start = taskid * chunk_size;
  39. int end = (taskid + 1) * chunk_size;
  40. if (taskid == numtasks - 1) {
  41. end = POLY_DEGREE + 1;
  42. }
  43.  
  44. printf("Task %d starts calculating: ", taskid);
  45. for (int i = start; i < end; i++) {
  46. float term_value = coefficients[i] * pow(X_VALUE, i);
  47. local_result += term_value;
  48. printf("%.2f*%.2f^%d = %.2f ", coefficients[i], X_VALUE, i, term_value);
  49. if (i < end - 1) {
  50. printf("; ");
  51. }
  52. }
  53. printf(", Partial Sum: %.2f\n", local_result);
  54.  
  55. MPI_Reduce(&local_result, &global_result, 1, MPI_FLOAT, MPI_SUM, MASTER, MPI_COMM_WORLD);
  56.  
  57. if (taskid == MASTER) {
  58. printf("Valoarea finala a polinomului evaluat in punctul %.2f este: %.2f\n", X_VALUE, global_result);
  59. }
  60.  
  61. MPI_Finalize();
  62. return 0;
  63. }
  64.  
Success #stdin #stdout #stderr 0.28s 40608KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted