Information Technology Reference
In-Depth Information
Dumping the solution array u to a file is performed by a dump method in a class IO :
class IO {
public static void dump (PrintStream f, double u[], double t0,
double dt)
{
int n = u.length;
double time = t0;
for(inti=0;i<n;i++){
f.println(time + " " + u[i]);
time += dt;
}
}
}
The main program can take this form:
class Demo {
public static void main (String argv[])
throws IOException
{
double tstop = Double.valueOf(argv[0]).doubleValue();
double dt = Double.valueOf(argv[1]).doubleValue();
int n = (int) (tstop/dt);
Func f = new f1();
double u0 = 1.0;
double u [] = Heun.advance (f, u0, dt, n);
double error = u[n] - Math.exp(-dt * n);
System.out.println("end value=" + u[n] + " error=" + error);
PrintStream file = new PrintStream(new FileOutputStream
("sol.dat"));
IO.dump (file, u, 0.0, dt);
file.close();
}
}
Plotting of the solution is subjected to the same comments as we made for C CC :
Calling a Java plotting library is possible, but there are no standard plotting tools to
be used.
6.4.6
Matlab
In Matlab, we implement Algorithm 6.12 as a function heun in an M-file heum.m :
function u = heun (f, u0, dt, n)
% HEUN numerical integration of ODEs by Heun's method
f = fcnchk(f);
u = zeros(n+1,1); % make n+1 zeros (as initialization)
% initial condition:
u(1) = u0;
% advance n steps:
for i = 1:n % i <-> i-1 compared to the original algorithm
v = feval(f, u(i));
u(i+1) = u(i) + 0.5 * dt * (v + feval(f, u(i) + dt * v));
%fprintf('u(%d)=%g\n',i+1,u(i+1))
end
As in Java, it is convenient to create arrays wherever we need them and return them
from functions, if desired. Matlab will automatically delete arrays when they are no
Search WWH ::




Custom Search