Euler's Algorithm using Java
The algorithm described at the beginning of this chapter is Euler's algorithm. As we've seen, the algorithm divides the region of interest into equal-sized intervals of horizontal size h, starting with the point representing the initial condition. Then off it goes, using the slope—the value of y' = f(xi, yi)—at the beginning of each interval to get to the point (xi+1, yi+1) at the other side of that interval. The set of all these points lies on the approximation to the solution function y(x). Until roundoff errors from the increased amount of computation overwhelms the solution, smaller values of h will result in better approximate solutions.[2] This is more traditionally called Euler's method, but we'll use the word algorithm here to avoid confusion with Java methods. Leonard Euler (1707–1783) was a brilliant and prolific mathematician whose career spanned more than 60 years. He contributed to number theory, geometry, and calculus, as well as several areas of science.
We can compute the next point (xi+1, yi+1) from the previous point (xi, yi) and the value of the slope yi' = f(xi, yi) at the previous point. Review
and, of course, xi+1 = xi + h.
Listing 8-0c shows the class DiffEqSolver in package numbercruncher. mathutils that will be the base class of the differential equation solver classes.
Listing 8-0c. The base class DiffEqSolver for the differential equation solver classes.
Code View: Scroll / Show All
package numbercruncher.mathutils;
/**
* The base class for differential equation solvers.
*/
public abstract class DiffEqSolver
{
/** the differential equation to solve */
protected DifferentialEquation equation;
/** the initial condition data point */
protected DataPoint initialCondition;
/** current x value */ protected float x;
/** current y value */ protected float y;
/**
* Constructor.
* @param equation the differential equation to solve
*/
public DiffEqSolver(DifferentialEquation equation)
{
this.equation = equation;
this.initialCondition = equation.getInitialCondition();
reset();
}
/**
* Reset x and y to the initial condition data point.
*/
public void reset()
{
this.x = initialCondition.x;
this.y = initialCondition.y;
}
/**
* Return the next data point in the
* approximation of the solution.
* @param h the width of the interval
*/
public abstract DataPoint nextPoint(float h);
}复制代码
Code View: Scroll / Show All
package numbercruncher.mathutils;
/**
* Differential equation solver that implements Euler's algorithm.
*/
public class EulersDiffEqSolver extends DiffEqSolver
{
/**
* Constructor.
* @param equation the differential equation to solve
*/
public EulersDiffEqSolver(DifferentialEquation equation)
{
super(equation);
}
/**
* Return the next data point in the
* approximation of the solution.
* @param h the width of the interval
*/
public DataPoint nextPoint(float h)
{
y += h*equation.at(x, y);
x += h;
return new DataPoint(x, y);
}
}复制代码