implement crank-nicolson in c++

implement crank-nicolson in c++

本文关键字:c++ in crank-nicolson implement      更新时间:2023-10-16

我想在c++中实现crank-nicolson方法:

−俄文(−1 j + 1) + 2 (1 + r) u (i, j + 1)−俄文(i + 1, j + 1) = 2(1−r) u (i, j) + r(u(i +1,j) + u(i+1,j))

我用高斯-约当法求解这个系统,但我不知道如何实现上面的公式。

const double pi=3.14159265;
double f (double x){
return sin(pi*x);
}
using namespace std;

//gauss-jordan
double* gauss(int n ,double **a){
    double factor;
    double *b,*x;
    x=new double[n];
    b=new double[n];

for (int k=1;k<=n;k++) {
  for (int i=1;i<=n;i++) {
    if (i!=k) {
     factor=a[i][k]/a[k][k];
     for (int j=1; j<=n; j++ ) {
       a[i][j]=a[k][j]*factor-a[i][j];
     }
b[i]=b[k]*factor -b[i];
    }
}
}
for (int i=1;i<=n;i++) {
 x[i]=b[i]/a[i][i];
}
return x;
}
int main()
{
    int i,j,n,m,xd,td;
    double h,k,r;
    double **t,**p;
    //----- initialize double pointer------------------
    double **u;
    u=new double *[m];
    for (int o=1;o<=m;o++){
        u[o]=new double [n];
    }
    //----- end of initialization-----------------------
   cout <<"nEnter the value of x dimension : n";
   cin >> xd;
   cout <<"nEnter the step size h for x dimension : n";
   cin >>h;
   cout <<"nEnter the value of time dimension : n";
   cin >>td;
   cout<<"nEnter the step k of time dimension : n";
   cin >>k;
   n=xd/h -1.0;
   m=td/k -1.0;
   cout <<"nnThe internal elements of x dimension are :"<<n;
   cout <<"nThe internal elements of t dimension are :"<<m;
   r=k/(h*h);
   cout <<"nThe r value is : "<<r;

   //initial conditions
    for (j=0;j<=m;j++){
    u[0][m]=0;
    u[10][m]=0;
    }
    //get the function
    for (i=1;i<n;i++){
    u[i][0]=f(i*h);
    }

    //apply crank-nicolson
    for (i=1;i<n;i++){
        for (j=1;j<n;j++){
              -r*u[i-1][j+1] +2.0*(1.0+r)*u[i][j+1] -r*u[i+1][j+1]=2.0*(1.0-r)*u[i][j] +r*(u[i-1][j]+u[i+1][j]);
    }  // here i can't figure the steps i must follow in order for this to work 

//-----delete double pointer-------------
    for(int o=1;o<m;o++){
    delete [] u[o];
    delete [] u;
    }
//---------------------------------------

    return 0;
}

我假设变量j表示时间步长。为了实现Crank-Nicolson,你必须把问题作为一个线性方程组来解决。该系统对应的矩阵将是三对角线形式,因此使用Thomas算法比使用Gauss-Jordan算法更好。

线性系统的形式为A x = b,其中x为向量(…u(张,j + 1), u (i, j + 1), u (i + 1, j + 1),…)和b的向量(…, r u(i - 1,j), 2(1 - r)u(i,j), r u(i+1,j),…)。矩阵A的第i行是这样的(0,…, 0,−r, 2(1 + r),−r, 0,…

关于有限差分方法,特别是Crank-Nicolson的一个很好的参考是John Strikwerda的书。

c++不是一个求解方程的系统。=不像数学中那样具有 = 的含义,而是表示赋值。

因此,像左边这样复杂的东西是没有意义的,你可能想做的是解这个方程,这样就有一个单独的变量被赋值,可能是用一个方程求解程序。