Advertisement
richarduie

MathUtilities.java

Jun 20th, 2013
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. /*
  2. Asked by Brian ( http://profile.yahoo.com/FZ6MESRR27BQISRYONDQEPJ5MM ) in Yahoo!Answers on June 20, 2013:
  3.  
  4. Inside a class MathUtilities, write a method calculateRoots which takes as input 3 doubles, representing the quadratic, linear, and constant...
  5. */
  6. public class MathUtilities
  7. {
  8.     public ComplexNumber[] calculateRoots( double a, double b, double c) {
  9.         ComplexNumber[] roots;
  10.         double B = (0 == b) ? 0 : -b;   // avoid using -0.0 when b is zero
  11.         double discriminant = b*b - 4*a*c;
  12.         if (0 == discriminant) {
  13.             roots = new ComplexNumber[ 1 ];
  14.             roots[0] = new ComplexNumber(B / (2*a), 0);
  15.         }
  16.         else if (0 < discriminant) {
  17.             roots = new ComplexNumber[ 2 ];
  18.             roots[0] = new ComplexNumber(
  19.                 (B - Math.sqrt( discriminant )) / (2*a), 0
  20.             );
  21.             roots[1] = new ComplexNumber(
  22.                 (B + Math.sqrt( discriminant )) / (2*a), 0
  23.             );
  24.         }
  25.         else {
  26.             roots = new ComplexNumber[ 2 ];
  27.             roots[0] = new ComplexNumber(
  28.                 B / (2*a), -Math.sqrt( -discriminant )/ (2*a)
  29.             );
  30.             roots[1] = new ComplexNumber(
  31.                 B / (2*a), Math.sqrt( -discriminant )/ (2*a)
  32.             );
  33.         }
  34.         return roots;
  35.     }
  36.    
  37.     public class ComplexNumber
  38.     {
  39.         private double real;
  40.         private double imaginary;
  41.         public ComplexNumber() {
  42.             this(0, 0);
  43.         }
  44.         public ComplexNumber( double r, double i) {
  45.             real = r;
  46.             imaginary = i;
  47.         }
  48.         public double[] get() {
  49.             double[] complex = new double[2];
  50.             complex[0] = real;
  51.             complex[1] = imaginary;
  52.             return complex;
  53.         }
  54.         public double getReal() {
  55.             return real;
  56.         }
  57.         public double getImaginary() {
  58.             return imaginary;
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement