|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | +#include <math.h> |
| 5 | +#include <time.h> |
| 6 | +#define M 300 |
| 7 | +void swap(double (*a)[M], double (*b)[M], int n) |
| 8 | +{ |
| 9 | + double swp; |
| 10 | + for (int i = 0; i < n; i++) { |
| 11 | + for (int j = 0; j < n; j++) { |
| 12 | + a[i][j] = b[i][j]; |
| 13 | + } |
| 14 | + } |
| 15 | +} |
| 16 | +double mmax(double (*phi)[M], double (*phip)[M], int n) |
| 17 | +{ |
| 18 | + double max = 0.0; |
| 19 | + double diff = 0.0; |
| 20 | + for (int i = 0; i < n; i++) { |
| 21 | + for (int j = 0; j < n; j++) { |
| 22 | + diff = fabs(phi[i][j]-phip[i][j]); |
| 23 | + if (diff > max) |
| 24 | + max = diff; |
| 25 | + } |
| 26 | + } |
| 27 | + return max; |
| 28 | +} |
| 29 | +double rho(double x, double y) |
| 30 | +{ |
| 31 | + double s1 = 0.6; |
| 32 | + double e1 = 0.8; |
| 33 | + double s2 = 0.2; |
| 34 | + double e2 = 0.4; |
| 35 | + |
| 36 | + if (x > s1 && x < e1 && y > s1 && y < e1) { |
| 37 | + return 1.0; |
| 38 | + } else if (x > s2 && x < e2 && y > s2 && y < e2 ) { |
| 39 | + return -1.0; |
| 40 | + } else { |
| 41 | + return 0.0; |
| 42 | + } |
| 43 | +} |
| 44 | +void run(double toler, double a) |
| 45 | +{ |
| 46 | + double epsilon0 = 8.85e-12; |
| 47 | + double a2; |
| 48 | + |
| 49 | + double (*phi)[M]; |
| 50 | + double (*phip)[M]; |
| 51 | + double (*rhoa)[M]; |
| 52 | + phi = malloc(sizeof(double[M][M])); |
| 53 | + phip = malloc(sizeof(double[M][M])); |
| 54 | + rhoa = malloc(sizeof(double[M][M])); |
| 55 | + |
| 56 | + int iter = 0; |
| 57 | + |
| 58 | + memset(phip, 0, sizeof(phip[0][0])*M*M); |
| 59 | + memset(phi, 0, sizeof(phi[0][0])*M*M); |
| 60 | + for (int i=1; i<M-1; i++) { |
| 61 | + for (int j=1; j<M-1; j++) { |
| 62 | + rhoa[i][j] = rho(i*a,j*a); |
| 63 | + } |
| 64 | + } |
| 65 | + double delta = 1.0; |
| 66 | + a2 = pow(a,2.0); |
| 67 | + while (delta > toler) { |
| 68 | + iter += 1; |
| 69 | + |
| 70 | + for (int i=1; i < M-1; i++) { |
| 71 | + for (int j=1; j < M-1; j++) { |
| 72 | + phip[i][j] = (phi[i+1][j] + phi[i-1][j] + |
| 73 | + phi[i][j+1] + phi[i][j-1])/4.0 + |
| 74 | + a2/(4.0 * epsilon0)*rhoa[i][j]; |
| 75 | + } |
| 76 | + } |
| 77 | + delta = mmax(phi, phip, M); |
| 78 | + swap(phi, phip, M); |
| 79 | + |
| 80 | + } |
| 81 | + printf("iters %d", iter); |
| 82 | + |
| 83 | +} |
| 84 | + |
| 85 | +int main(int argc, char *argv[]) |
| 86 | +{ |
| 87 | + clock_t start = clock(); |
| 88 | + run(1e-6, 0.01); |
| 89 | + clock_t end = clock(); |
| 90 | + double total = ((double)(end - start)) / CLOCKS_PER_SEC; |
| 91 | + printf("Execution time: %f\n",total); |
| 92 | +} |
0 commit comments