| 1 | = Ex5.c = |

| 2 | {{{#!C |

| 3 | /* |

| 4 | Large Scale Computing |

| 5 | Heat/Mass Transfer |

| 6 | ex5.c : SOR |

| 7 | */ |

| 8 | #include<stdio.h> |

| 9 | #include<stdlib.h> |

| 10 | #include<math.h> |

| 11 | |

| 12 | int main(int argc, char **argv){ |

| 13 | double a,b,d; |

| 14 | double *phi; |

| 15 | double w; |

| 16 | double *rhs; |

| 17 | double dx; |

| 18 | double err,merr; |

| 19 | double tol = 1.0e-5; |

| 20 | double rlx = 1.8; |

| 21 | int i,num,itc; |

| 22 | FILE *fp; |

| 23 | |

| 24 | if (argc < 5){ |

| 25 | printf("Usage:%s [NUM] [A] [B] [D]\n",argv[0]); |

| 26 | exit(-1); |

| 27 | } |

| 28 | |

| 29 | /* set parameters */ |

| 30 | num = atoi(argv[1]); |

| 31 | a = atof(argv[2]); |

| 32 | b = atof(argv[3]); |

| 33 | d = atof(argv[4]); |

| 34 | |

| 35 | printf("num=%d A=%e B=%e D=%e\n",num,a,b,d); |

| 36 | |

| 37 | /* Memory Allocation and Check*/ |

| 38 | phi = (double *)calloc(num, sizeof(double)); |

| 39 | if (phi == (double *)NULL){ |

| 40 | printf("Memory Allocation Failed\n"); |

| 41 | exit(-1); |

| 42 | } |

| 43 | |

| 44 | rhs = (double *)calloc(num, sizeof(double)); |

| 45 | if (rhs == (double *)NULL){ |

| 46 | printf("Memory Allocation Failed\n"); |

| 47 | exit(-1); |

| 48 | } |

| 49 | |

| 50 | /** Setup **/ |

| 51 | dx = 1.0 / (double)(num - 1); |

| 52 | for (i = 0 ; i < num ; i++){ |

| 53 | rhs[i] = -dx * dx / d * (dx * (double)i); |

| 54 | phi[i] = 0.0; |

| 55 | } |

| 56 | |

| 57 | /* Boundary Condition*/ |

| 58 | phi[0] = a; |

| 59 | phi[num-1] = b; |

| 60 | |

| 61 | /* Solve with SOR Method*/ |

| 62 | itc = 0; |

| 63 | while(1){ |

| 64 | /* update phi & Check Convergence */ |

| 65 | merr = 0.0; |

| 66 | for (i = 1 ; i < (num - 1) ; i++){ |

| 67 | w = -0.5 * (rhs[i] - phi[i + 1] - phi[i - 1]); |

| 68 | err = fabs(w - phi[i]); |

| 69 | phi[i] += rlx * (w - phi[i]); |

| 70 | if (merr < err) merr = err; |

| 71 | } |

| 72 | |

| 73 | itc++; |

| 74 | if (merr < tol) break; |

| 75 | if ((itc % 100) == 0) printf("itc=%d err=%e\n",itc,merr); |

| 76 | } |

| 77 | |

| 78 | printf("Number of Iteration=%d\n",itc); |

| 79 | |

| 80 | /* Output Result */ |

| 81 | fp = fopen("res.dat","w"); |

| 82 | if (fp == NULL){ |

| 83 | printf("File could not create\n"); |

| 84 | exit(-1); |

| 85 | } |

| 86 | |

| 87 | for (i = 0 ; i < num ; i++){ |

| 88 | fprintf(fp,"%e %e\n",dx * (double)i,phi[i]); |

| 89 | } |

| 90 | fclose(fp); |

| 91 | |

| 92 | /* END : Deallocate Memory */ |

| 93 | free(phi); |

| 94 | free(rhs); |

| 95 | printf("Done\n"); |

| 96 | } |

| 97 | }}} |