/* Example Three Example of the use of the class RungeKutta demonstrating the use of the instance methods in solving a single ordinary differential equation: dy/dx = a.x.sqrt(1.0 - y*y) Michael Thomas Flanagan m.flanagan@ee.ucl.ac.uk Updated January 2010 */ import flanagan.integration.*; // Class to demonstrate the fourth order Runge-Kutta method in class RungeKutta. public class RungeKuttaExampleThree{ public static void main(String[ ] arg){ // Create instance of the class holding the derivative evaluation method Deriv d1 = new Deriv(); // Assign values to constants in the derivative function double a = 10.0D; d1.setA(a); // Variable declarations double x0 = 0.0D; // initial value of x double y0 = 0.0D; // initial value of y double xn = 1.0D; // final value of x double yn = 0.0D; // returned value of y at x = xn double h = 0.01D; // step size // Create an instance of RungeKutta RungeKutta rk = new RungeKutta(); // Set values needed by fixed step size method rk.setInitialValueOfX(x0); rk.setFinalValueOfX(xn); rk.setInitialValuesOfY(y0); rk.setStepSize(h); // Call Fourth Order Runge-Kutta method yn = rk.fourthOrder(d1); // Output the result System.out.println("Fourth order Runge-Kutta procedure"); System.out.println("The value of y at x = " + xn + " is " + yn); System.out.println("Number of iterations = " + rk.getNumberOfIterations()); // Set additional values needed by fixed step size method rk.setToleranceScalingFactor(1e-5); rk.setToleranceAdditionFactor(1e-3); // Call Fehlberg-Runge-Kutta method yn = rk.fehlberg(d1); // Output the result System.out.println("\nFehlberg-Runge-Kutta procedure"); System.out.println("The value of y at x = " + xn + " is " + yn); System.out.println("Number of iterations = " + rk.getNumberOfIterations()); // Call Cash-Karp-Runge-Kutta method yn = rk.cashKarp(d1); // Output the result System.out.println("\nCash-Karp-Runge-Kutta procedure"); System.out.println("The value of y at x = " + xn + " is " + yn); System.out.println("Number of iterations = " + rk.getNumberOfIterations()); } } // Class to evaluate the derivative dy/dx = a.x.sqrt(1.0 + y*y) for given values of x and y. class Deriv implements DerivFunction{ private double a = 0.0D; public double deriv(double x, double y){ double dydx = a*x*Math.sqrt(1.0 + y*y); return dydx; } public void setA(double a){ this.a = a; } }