Professional Documents
Culture Documents
Δt ≤
( Δx ) or
2
Fo =
αΔt 1
≤
4α
( Δx )
2 4
Fo is the finite‐difference form of Fourier number.
The following is the code to solve a problem with constant value boundary
condition (Dirichlet boundary condition).
//===========================================================================
// Name : pdu1undsteady.cpp
// Author : Pengfei Du, Mechanical Engineering, Univ. of Iowa.
// Description : Simple one dimensional heat transfer problem solved using
// finite difference method.
//===========================================================================
#include <iostream>
#include <fstream>
using namespace std;
class pdu1dsteadyExp{
private:
float dx,dt,xSize,tTotal;
int xGridNum;
float K;
double **LHS,*RHS,*solutionLast,*solutionNew,*x;
ofstream myfile;
public:
http://www.pengfeidu.net/
void setMatParam(float k){
K=k; //thermal diffusivity;
}
float source(float xPos,float time){
return xPos*time*1000;
}
void setGeoParam(float xL, float t, int xIntNum, float tInc){
xSize = xL; //length of domain;
tTotal = t; //total calculation time;
dt = tInc; //time step increasement;
xGridNum = xIntNum;
dx = xL/xIntNum;
x = new double[xGridNum+1];
for (int i=0;i<=xGridNum;i++) x[i]=i*dx; //setup coordinate;
}
void setInitValue(){
for(int i=1;i<xGridNum;i++) {
solutionLast[i] = 100;
solutionNew[i] = 100;
}
solutionLast[0]=10; //left boundary temperature is 10;
solutionLast[xGridNum]=120; //right temperature is 120;
myfile.open("result.txt");
}
bool checkStability(){
cout<<"dx= "<<dx<<" and dt="<<dt<<endl;
return K*dt/dx/dx<0.25;
}
void allocating(){
//Allocates memory:
RHS = new double[xGridNum+1]; //RHS is a pointer, "new" will allocate
//a part of memory which are addresses pointing to doubles.
solutionLast = new double[xGridNum+1];
solutionNew = new double[xGridNum+1];
//allocate multi-dimensional array (2d here for this case);;
LHS = new double* [xGridNum+1];
for(int i=0;i<=xGridNum;i++) LHS[i]=new double [xGridNum+1];
setInitValue();
}
void solve(){
int j=0;
while(j<tTotal/dt){
solutionNew[0]=10;
solutionNew[xGridNum]=120;
for(int k=1;k<xGridNum;k++){
solutionNew[k] = solutionLast[k]+dt*(K/dx/dx*
(solutionLast[k-1]+solutionLast[k+1]-2.*solutionLast[k]
+source(x[k],j*dt))
);
}
j++;
solutionLast=solutionNew;
myfile<<"#"<<j<<endl;
for(int k=0;k<=xGridNum;k++)
myfile<<*(x+k)<<" "<<*(solutionNew+k)<<endl;
http://www.pengfeidu.net/
myfile<<endl;
myfile<<endl;
}
myfile.close();
}
void deallocating(){
delete [] RHS; //deallocate 1d array;
delete [] x;
for(int i=0;i<=xGridNum;i++) delete [] LHS[i];
delete [] LHS;
}
};
int main() {
pdu1dsteadyExp pdu1d;
pdu1d.setGeoParam(1.,.01,20,0.0005);
pdu1d.setMatParam(1.);
pdu1d.checkStability()==true?cout<<"Algorithm is stable.\n":cout<<"Algorithm isn't stable.\n";
pdu1d.allocating();
pdu1d.solve();
pdu1d.deallocating();
cout<<"\nCalculation is done.";
return 0;
}
http://www.pengfeidu.net/