wiki:cypress/Programming/HeatMassTransfer/ex3.c

Ex3.c

/*
  Large Scale Computing
  Heat/Mass Transfer
  ex3.c 
 */
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
 
int main(int argc, char **argv){
  double a,b,d;
  double *phi,*phi0;
  double *rhs;
  double dx;
  double err,merr;
  double tol = 1.0e-8;
  int i,num,itc;
  FILE *fp;
 
  if (argc < 5){
    printf("Usage:%s [NUM] [A] [B] [D]\n",argv[0]);
    exit(-1);
  }
 
  /* set parameters */
  num = atoi(argv[1]);
  a = atof(argv[2]);
  b = atof(argv[3]);
  d = atof(argv[4]);
 
  printf("num=%d A=%e B=%e D=%e\n",num,a,b,d);
 
  /* Memory Allocation and Check*/
  phi = (double *)calloc(num, sizeof(double));
  if (phi == (double *)NULL){
    printf("Memory Allocation Failed\n");
    exit(-1);    
  }
 
  phi0 = (double *)calloc(num, sizeof(double));
  if (phi0 == (double *)NULL){
    printf("Memory Allocation Failed\n");
    exit(-1);    
  }
 
  rhs = (double *)calloc(num, sizeof(double));
  if (rhs == (double *)NULL){
    printf("Memory Allocation Failed\n");
    exit(-1);    
  }  
 
  /** Setup **/
  dx = 1.0 / (double)(num - 1);
  for (i = 0 ; i < num ; i++){
    rhs[i] = -dx * dx / d * (dx * (double)i); 
    phi[i] = phi0[i] = 0.0;
  }
 
  /* Boundary Condition*/
  phi[0] = phi0[0] = a;
  phi[num-1] = phi0[num-1] = b;
 
  /* Solve with Jacobi Method*/
  itc = 0;
  while(1){
    /* update phi */
    for (i = 1 ; i < (num - 1) ; i++){
      phi[i] = -0.5 * (rhs[i] - phi0[i + 1] - phi0[i - 1]);
    }
 
    /* Check Convergence */
    merr = 0.0;
    for (i = 0 ; i < num ; i++){
      err = fabs(phi[i] - phi0[i]);
      if (merr < err) merr = err;
      phi0[i] = phi[i];
    }
 
    itc++;
    if (merr < tol) break;
    if ((itc % 10000) == 0) printf("itc=%d err=%e\n",itc,merr);
  }
 
  printf("Number of Iteration=%d\n",itc);
 
  /* Output Result */
  fp = fopen("res.dat","w");
  if (fp == NULL){
    printf("File could not create\n");
    exit(-1);
  }
 
  for (i = 0 ; i < num ; i++){
    fprintf(fp,"%e %e\n",dx * (double)i,phi[i]);
  }
  fclose(fp);
 
  /* END : Deallocate Memory */
  free(phi);
  free(phi0);
  free(rhs);
  printf("Done\n");
}
Last modified 4 years ago Last modified on May 14, 2015 3:11:29 PM