Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

// Explicit method for the heat equation

//
// du/dt = d^2u/dx^2,
// boundary conditions:
// u(t,pi)=u(t,0)=exp(-4*t) for 0 <= t <= 1
// u(0,x)=cos(2*x) for 0 <= x <= pi
//

#include <iostream>
#include <cmath>
#include <armadillo>

using namespace std;


using namespace arma;

int main()
{

double m = 500;
double n = 40;
double T = 1;
double X = 2*acos(0.0); // this is actually pi, or can use 22/7
double h = T / m;
double k = X / n;
double a = h / (k*k);

mat u(m+1,n+1,fill::zeros); // the solution

cout << "m = " << m << ", n = " << n << endl;
cout << "h = " << h << ", k = " << k << endl;
cout << "matrix first 5 rows" << endl; //
cout << u(span(0,4),span(0,n)) << endl;//

// Now we will initialize the matrix

int i, j; // so that u[i,j] = u(i*h, j*k)

for (i=0; i <= m; i++) {


u(i,0) = exp(-4*i*h);
u(i,n) = exp(-4*i*h);
}

for (j=0; j <= n; j++) {


u(0, j) = cos(2*j*k);
}

double squaredError = 0.0;


for (i=1; i<=m; i++) {
for (j=1; j<n; j++) {
u(i,j) = a*u(i-1,j+1) + (1.0-2.0*a)*u(i-1,j) + a*u(i-1,j-1);
squaredError += pow(u(i,j) - exp(-4*i*h)*cos(2*j*k), 2);
}
}

cout << "Total squared error = " << squaredError << endl;
u.save("explicit_heat.csv",csv_ascii);
system("pause");
return 0;
}

You might also like