-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
94 lines (74 loc) · 1.7 KB
/
main.cpp
File metadata and controls
94 lines (74 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <armadillo>
#include <fstream>
#include <time.h>
#include "tridiag.h"
using namespace arma;
using namespace std;
//Schemes for solving diffusion equation
void ForwardEuler(double alpha, vec &u)
{
u = trimul(alpha,1-2*alpha,alpha,u);
}
void BackwardEuler(double alpha, vec &u)
{
vec v = u;
trisolve(-alpha, 1+2*alpha, -alpha, u,v);
}
void CrankNicolson(double alpha, vec &u)
{
ForwardEuler(alpha/2, u);
BackwardEuler(alpha/2, u);
}
void solve(double dt, double dx, double T, vec v,
void (*method)(double, vec&),
const char* outfile )
{
ofstream out(outfile);
double alpha = dt/(dx*dx);
bool print1 = false;
bool print2 = false;
for(double t=0; t<T; t+=dt)
{
//update v
method(alpha,v);
//print to file
if (t>=0.02 && !print1)
{
out << v.t();
print1 = true;
}
else if (t>=0.5 && !print2)
{
out<<v.t();
print2 = true;
}
//out << v.t();
}
}
int main ()
{
//steps
double dx = 0.1;
double dt = 0.49*dx*dx;
//total time
double T = 2;
//initial state
int n = 9;
vec v(n);
for(int i = 0; i < n ; i++)
v(i) = -1 + (i+1)*dx;
clock_t start, mid1, mid2, end;
start = clock();
solve(dt, dx, T, v, *ForwardEuler, "ForwardEuler.dat");
mid1 = clock();
solve(dt, dx, T, v, *BackwardEuler, "BackwardEuler.dat");
mid2 = clock();
solve(dt, dx, T, v, *CrankNicolson, "CrankNicolson.dat");
end = clock();
double cps = CLOCKS_PER_SEC;
double FEtime = (mid1-start)/cps;
double BEtime = (mid2-mid1)/cps;
double CNtime = (end-mid2)/cps;
cout << FEtime <<"\t" << BEtime << "\t" <<CNtime<<endl;
return 0;
}