歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> MPI 並行解方程

MPI 並行解方程

日期:2017/3/1 10:13:29   编辑:Linux編程

基本算法 逐步縮小函數值異號的范圍 最後逼近最終解

所有線程計算中地位相同 計算范圍與self號相應的區段值 把x較小值做為解 只支持單個解

lx做為計算范圍和終止條件 最後 由主線程顯示結果

  1. #include "mpi.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define END 999999
  5. #define CON 1
  6. #define RES 2
  7. //calculation values
  8. #define OST 0.000001
  9. #define IL 0.5
  10. #define IH 1.5
  11. #define THD 0.0001
  12. float func(float x) {
  13. //any function
  14. return (x*x-1);
  15. }
  16. int main(int argc,char *argv[]) {
  17. int self,size;
  18. MPI_Init(&argc,&argv);
  19. MPI_Comm_rank(MPI_COMM_WORLD,&self);
  20. MPI_Comm_size(MPI_COMM_WORLD,&size);
  21. MPI_Request r;
  22. MPI_Status s;
  23. float lx=IL,hx=IH;//end point value
  24. float res=END;
  25. float *data=(float *)malloc(size*sizeof(float));//for gather
  26. while(((hx-lx)/size>THD)&&(END!=lx)) {
  27. res=END;
  28. float step=(hx-lx)/size;
  29. lx=lx+step*(self);
  30. hx=lx+step-OST;
  31. float lv=func(lx);
  32. float hv=func(hx);
  33. if(lv*hv<0) {
  34. //continue calculation
  35. } else {
  36. if(0==lv) {
  37. //end and mark to pass low to root
  38. res=lx;
  39. } else if(0==hv) {
  40. //end and mark to pass high to root
  41. res=hx;
  42. } else {
  43. //wait for a new lx hx
  44. }
  45. lx=END;
  46. }
  47. //gather all lx
  48. MPI_Allgather(&lx,1,MPI_FLOAT,data,1,MPI_FLOAT,MPI_COMM_WORLD);
  49. int prc=END;
  50. for(int i=0;i<size;++i) {
  51. if(END!=data[i]) {
  52. prc=i;
  53. lx=data[i];
  54. }
  55. }
  56. if(END==prc) {//all ends
  57. if(END!=res) {//send res to root
  58. MPI_Ssend(&res,1,MPI_FLOAT,0,0,MPI_COMM_WORLD);
  59. }
  60. } else {
  61. MPI_Bcast(&hx,1,MPI_FLOAT,prc,MPI_COMM_WORLD);
  62. }
  63. }
  64. if(0==self) {//show result
  65. if(END==lx) {
  66. MPI_Recv(&lx,1,MPI_FLOAT,MPI_ANY_SOURCE,0,MPI_COMM_WORLD,&s);
  67. for(int i=0;i<size;++i) {
  68. if(END!=data[i]) {
  69. lx=data[i];
  70. }
  71. }
  72. } else {
  73. lx=(hx+lx)/2;
  74. }
  75. printf("result %f \n",lx);
  76. }
  77. free(data);
  78. MPI_Finalize();
  79. return 0;
  80. }
Copyright © Linux教程網 All Rights Reserved