Solver.java


Below is the syntax highlighted version of Solver.java from §9.5 Numerical Solutions to Differential Equations.



/******************************************************************************
 *  Compilation:  javac Solver.java
 *  Execution:    java Solver a b c d
 *
 *  Solve system of equations:  ax + y = c, x + by = d by two methods.
 *
 *  Method 1:  isolate x from first equation:  x = (c - y) / a
 *             substitute into second equation and solve for y:  y = (d - c/a) / (b - 1/a)
 *
 *  Method 2:  isolate x from second equation:  x = d - by
 *             substitute into first equation and solve for y:  y = (c - ad) / (1 - ab)
 *
 *
 *  % java Solver 1e-17 2 1 3
 *  Method 1:  0.0, 1.0        (wrong)
 *  Method 2:  1.0, 1.0        (right)
 *
 *  % java Solver 1 2 1 3
 *  Method 1:  -1.0, 2.0       (right)
 *  Method 2:  -1.0, 2.0       (right)

 ******************************************************************************/

public class Solver {

   public static void main(String[] args) {
      double a = Double.parseDouble(args[0]);
      double b = Double.parseDouble(args[1]);
      double c = Double.parseDouble(args[2]);
      double d = Double.parseDouble(args[3]);

      // solution method 1
      double y1 = (d - c/a) / (b - 1/a);
      double x1 = (c - y1) / a;
      StdOut.println(x1 + ", " + y1);

      // solution method 2
      double y2 = (c - a*d) / (1 - a*b);
      double x2 = d - b*y2;
      StdOut.println(x2 + ", " + y2);
   }

}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:36:03 EDT 2022.