Advertisement
Guest User

calc int

a guest
Mar 26th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.86 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <mpi.h>
  5. // functia de integrat f(x)
  6. double f(double x)
  7. {
  8. return 4.*sqrt(1.-x*x);
  9. }
  10.  
  11. double
  12. calculeaza_integrala (double a ,double b , long N )
  13. {
  14. int i ;
  15. double dx = ( b - a )/( double ) N;
  16. double x ;
  17. double s ;
  18. s = 0;
  19. for ( i =0; i < N ; i ++)
  20. {
  21. x = a + ( double ) i * dx + dx /2.;
  22. s = s + f ( x);
  23. }
  24. s = s * dx ;
  25. return s ;
  26. }
  27. int main ( int argc , char ** argv )
  28. {
  29. int Np , rank;
  30. long i ;
  31. // limitele de integrare
  32. double a , b ;
  33. double N ;
  34. double c1 , c2;
  35.  
  36. long Ni;
  37. MPI_Init ( &argc , &argv);
  38. MPI_Comm_size(MPI_COMM_WORLD, &Np);
  39. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  40. // MASTER -- rang 0
  41. if(rank==0)
  42. {
  43. double s,I;
  44. // input
  45. a = 0.;
  46. b= 1.;
  47. N= 10000;
  48. // trimite a, b catre procesele de tip worker
  49. for(i=1;i<Np;i++)
  50. {
  51. // trimite intervalul de integrare [c1,c2]
  52. c1=a+ (b-a)/(double)(Np-1) * (double)(i-1);
  53. c2=a+ (b-a)/(double)(Np-1) * (double)i;
  54. Ni= (long) ( (double)N/(double)(Np-1) );
  55. MPI_Send( &c1, 1,MPI_DOUBLE,i, 0,MPI_COMM_WORLD);
  56. MPI_Send( &c2, 1,MPI_DOUBLE,i, 0,MPI_COMM_WORLD);
  57. MPI_Send( &Ni, 1,MPI_LONG,i, 0,MPI_COMM_WORLD);
  58. }
  59. // primeste rezultatele integralelor si calculeaza rezultatul final
  60. for(i=1;i<Np;i++)
  61. {
  62. MPI_Recv( &s, 1,MPI_DOUBLE,MPI_ANY_SOURCE, 0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  63. I=I+s;
  64. }
  65. // afiseaza rezultatul integralei
  66. printf("I = %f \n",I);
  67. }
  68. // WORKERS -- rangurile 1, 2, ... ,
  69. else
  70. {
  71. double s;
  72. //primeste intervalul de integrare
  73. MPI_Recv( &c1, 1,MPI_DOUBLE, 0, 0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  74. MPI_Recv( &c2, 1,MPI_DOUBLE, 0, 0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  75. MPI_Recv( &Ni, 1,MPI_LONG, 0, 0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  76. // calculeaza integrala pe intervalul [c1,c2]
  77. s=calculeaza_integrala(c1,c2,Ni);
  78. // trimite rezultatul catre MASTER
  79. MPI_Send( &s, 1,MPI_DOUBLE, 0, 0,MPI_COMM_WORLD);
  80. }
  81. MPI_Finalize();
  82. return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement