Version 3


public class QuadraticEquation {
  // a quadratic equation a*x^2 + b*x + c = 0
  
  double a;
  double b;
  double c;
  
  QuadraticEquation(double a1, double b1, double c1) {
    // create a new quadratic equation with the given coefficients
    a = a1;
    b = b1;
    c = c1;
  }
  
  private String toSignedString(double d) {
    // creates string with sign from double value
    if (d >= 0) {
      return("+ " + Double.toString(d));
    } 
    else {
      return("- " + Double.toString(-d));
    }
  }      

  private double discriminant() {
    // the discriminant of the equation
    return(b*b/(4*a*a) - c/a); 
  }

  double[] getSolution() {
    // returns vector of solution values
    double a1 = -b/(2*a);
    double d = discriminant();
    double[] result;

    if (d > 0) {
      result = new double[2];
      double dRoot = Math.sqrt(d);
      result[0] = a1 + dRoot;
      result[1] = a1 - dRoot;
    } 
    else if (d == 0) {
      result = new double[1];
      result[0] = a1;
    }
    else {
      // d<0: result is empty
      result = new double[0];
    }
    
    return(result);
  }

  void print() {
    // print the equation to the screen
    System.out.println(a + "*x^2 "+ toSignedString(b) + "*x " 
		       + toSignedString(c));
  }
}

public class TestQuadraticEquation {
  // simple test program for QuadraticEquation

  public static void main (String[] args) {
    // get the coefficients from the command line
    double a = Double.parseDouble(args[0]);
    double b = Double.parseDouble(args[1]);
    double c = Double.parseDouble(args[2]);

    QuadraticEquation qe1 = new QuadraticEquation(a, b, c);

    System.out.println("The quadratic equation");
    qe1.print();
    
    double[] result = qe1.getSolution();
    int      count =  result.length;
    System.out.println("has " + count + " solutions");
    
    if (count > 0) {
      System.out.println(result[0]);
    }
    if (count > 1) {
      System.out.println(result[1]);
    }
  }
}

previous    contents     next

Peter Junglas 8.3.2000