![]() |
![]() |
![]() |
Demo: The 1-D heat equation
This code illustrates the numerical solution of the 1-D heat equation using a finite difference scheme.
const double L = 1.;
ofstream pf("output.dat");
|
size_t nx = atoi(argv[1]); double h = L/double(nx); theTimeStep = atof(argv[2]); theFinalTime = 1.; |
Vect<double> x, f(nx+1), u(nx+1), v(nx+1);
x.setUniform(0.,L,nx+1);
u.set("sin(pi*x)",x);
|
TimeLoop {
|
f.setTime(theTime);
f.set("exp(t)*sin(pi*x)*(1+pi^2)",x);
for (int i=2; i<=nx; i++) {
A(i,i ) = 1./theTimeStep + 2./(h*h);
A(i,i+1) = -1./(h*h);
A(i,i-1) = -1./(h*h);
v(i) = u(i)/theTimeStep + f(i);
}
|
A(1,1) = 1./theTimeStep;
A(1,2) = 0.;
v(1) = 0.;
A(nx+1,nx+1) = 1./theTimeStep;
A(nx+1,nx) = 0.;
v(nx+1) = 0.;
|
A.solve(v);
u = v;
|
for (size_t i=1; i<=nx+1; i++)
pf << x(i) << " " << u(i) << endl;
pf << endl;
}
|
![]() |
![]() |
![]() |