Advertisement
richarduie

Quadratic Equations in Java

Oct 29th, 2013
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.85 KB | None | 0 0
  1. First, you need to anticipate the possibility of complex roots.
  2. -----------------
  3. public class ComplexNumber
  4. {
  5.     private double real;
  6.     private double imaginary;
  7.     public ComplexNumber() {
  8.         this(0.0, 0.0);
  9.     }
  10.     public ComplexNumber( double real, double imaginary ) {
  11.         this.real = real;
  12.         this.imaginary = imaginary;
  13.     }
  14.  
  15.     public double[] get() {
  16.         double[] complex = new double[2];
  17.         complex[0] = real;
  18.         complex[1] = imaginary;
  19.         return complex;
  20.     }
  21.     public double[] set( double[] complex) {
  22.         double[] old = new double[2];
  23.         old[0] = real;
  24.         old[1] = imaginary;
  25.         real = complex[ 0 ];
  26.         imaginary = complex[ 1 ];
  27.         return old;
  28.     }
  29.     public double getReal() {
  30.         return real;
  31.     }
  32.     public double setReal( double real ) {
  33.         double old = this.real;
  34.         this.real = real;
  35.         return old;
  36.     }
  37.     public double getImaginary() {
  38.         return imaginary;
  39.     }
  40.     public double setImaginary( double imaginary ) {
  41.         double old = this.imaginary;
  42.         this.imaginary = imaginary;
  43.         return old;
  44.     }
  45.  
  46.     public String toString() {
  47.         StringBuffer sb = new StringBuffer();
  48.         sb.append( (0 != real) ? Double.toString( real ):"");
  49.         sb.append( (0 != real && 0 != imaginary) ? " + ":"");
  50.         sb.append( (0 != imaginary) ? Double.toString( imaginary ) + "i":"");
  51.         return sb.toString();
  52.     }
  53. }
  54. -----------------
  55.  
  56. Next, handle extracting and reporting the roots of quadratic equations.
  57. -----------------
  58. public class QuadraticEquation
  59. {
  60.     public ComplexNumber[] calculateRoots(double[] coefficients) {
  61.         // calculate the roots of the quadratic equation 0 = ax² + bx + c
  62.         // for coefficients a, b, and c where a = coefficients[ 0 ],
  63.         // b = coefficients[ 1 ], and c = coefficients[ 2 ]
  64.         // ...defer to worker signature
  65.         return calculateRoots(
  66.             coefficients[ 0 ], coefficients[ 1 ], coefficients[ 2 ]
  67.         );
  68.     }
  69.     public ComplexNumber[] calculateRoots(double a, double b, double c) {
  70.         // calculate the roots of the quadratic equation 0 = ax² + bx + c
  71.         // for coefficients a, b, and c
  72.         ComplexNumber[] roots;
  73.         double B = (0 == b) ? 0 : -b; // avoid using -0.0 when b is zero
  74.         double discriminant = b * b - 4 * a * c;
  75.         if (0 == discriminant) {
  76.             roots = new ComplexNumber[1];
  77.             roots[0] = new ComplexNumber(B / (2 * a), 0.0);
  78.         } else if (0 < discriminant) {
  79.             roots = new ComplexNumber[2];
  80.             roots[0] = new ComplexNumber(
  81.                 (B - Math.sqrt(discriminant)) / (2 * a), 0
  82.             );
  83.             roots[1] = new ComplexNumber(
  84.                 (B + Math.sqrt(discriminant)) / (2 * a), 0 
  85.             );
  86.         } else {
  87.             roots = new ComplexNumber[2];
  88.             roots[0] = new ComplexNumber(
  89.                 B / (2 * a), -Math.sqrt(-discriminant)/ (2 * a)
  90.             );
  91.             roots[1] = new ComplexNumber(
  92.                 B / (2 * a), Math.sqrt(-discriminant) / (2 * a)
  93.             );
  94.         }
  95.         return roots;
  96.     }
  97.  
  98.     public void print(double[] coefficients, ComplexNumber[] roots) {
  99.         String c = "\nFor the quadratic equation 0 = ax² + bx + c " +
  100.             "with a = " + coefficients[0] + ", b = " + coefficients[1] +
  101.             ", and c = " + coefficients[2];
  102.  
  103.         String r;
  104.         if (1 == roots.length) {
  105.             r = ",\nthe single root is x = " + (roots[0]).toString();
  106.         }
  107.         else {
  108.             r = ",\nthe two distinct roots are:" +
  109.                 "  x₁ = "+ (roots[0]).toString() +
  110.                 "  and  x₂ = " + (roots[1]).toString();
  111.         }
  112.  
  113.         System.out.println( c + r );
  114.     }
  115. }
  116. -----------------
  117.  
  118. Finally, manage input collection and use of the QuadraticEquation class.
  119. -----------------
  120. import java.util.InputMismatchException;
  121. import java.util.Scanner;
  122.  
  123.  
  124. public class QuadraticEquationRunner
  125. {
  126.     public static void main( String[] args) {
  127.         // collect user inputs for coefficients a, b, and c of the
  128.         // quadratic equation: 0 = ax² + bx + c
  129.         double[] coefficients = readCoefficients();
  130.  
  131.         QuadraticEquation qe = new QuadraticEquation();
  132.         ComplexNumber[] roots = qe.calculateRoots( coefficients );
  133.         qe.print( coefficients, roots );
  134.     }
  135.  
  136.     private static double[] readCoefficients() {
  137.         Scanner scan = new Scanner( System.in );
  138.         double[] coefficients = new double[ 3 ];
  139.         System.out.println(
  140.             "For the quadratic equation: 0 = ax² + bx + c:"
  141.         );
  142.         coefficients[ 0 ] = readDouble(
  143.             "1) enter coefficient a (for x² term)", scan
  144.         );
  145.         coefficients[ 1 ] = readDouble(
  146.             "2) enter coefficient b (for x term)", scan
  147.         );
  148.         coefficients[ 2 ] = readDouble(
  149.             "3) enter c (constant term)", scan
  150.         );
  151.         return coefficients;
  152.     }
  153.     private static double readDouble( String prompt, Scanner scan ) {
  154.         double d = 0;  // set return into method-global scope
  155.         // read until valid input given
  156.         while (true) {
  157.             System.out.println( prompt );
  158.             try {
  159.                 d = scan.nextDouble();
  160.                 break;
  161.             }
  162.             catch( InputMismatchException e ) {
  163.                 String sink = scan.next();
  164.                 System.out.println(
  165.                     "invalid value: " + sink + "\n" +
  166.                     e.toString()
  167.                 );
  168.             }
  169.         }
  170.         return d;
  171.     }
  172. }
  173.  
  174. -----------------
  175.  
  176. Put these in the same package and run the QuadraticEquationRunner as a Java app.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement