Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Asked by Brian ( http://profile.yahoo.com/FZ6MESRR27BQISRYONDQEPJ5MM ) in Yahoo!Answers on June 20, 2013:
- Inside a class MathUtilities, write a method calculateRoots which takes as input 3 doubles, representing the quadratic, linear, and constant...
- */
- public class MathUtilities
- {
- public ComplexNumber[] calculateRoots( double a, double b, double c) {
- ComplexNumber[] roots;
- double B = (0 == b) ? 0 : -b; // avoid using -0.0 when b is zero
- double discriminant = b*b - 4*a*c;
- if (0 == discriminant) {
- roots = new ComplexNumber[ 1 ];
- roots[0] = new ComplexNumber(B / (2*a), 0);
- }
- else if (0 < discriminant) {
- roots = new ComplexNumber[ 2 ];
- roots[0] = new ComplexNumber(
- (B - Math.sqrt( discriminant )) / (2*a), 0
- );
- roots[1] = new ComplexNumber(
- (B + Math.sqrt( discriminant )) / (2*a), 0
- );
- }
- else {
- roots = new ComplexNumber[ 2 ];
- roots[0] = new ComplexNumber(
- B / (2*a), -Math.sqrt( -discriminant )/ (2*a)
- );
- roots[1] = new ComplexNumber(
- B / (2*a), Math.sqrt( -discriminant )/ (2*a)
- );
- }
- return roots;
- }
- public class ComplexNumber
- {
- private double real;
- private double imaginary;
- public ComplexNumber() {
- this(0, 0);
- }
- public ComplexNumber( double r, double i) {
- real = r;
- imaginary = i;
- }
- public double[] get() {
- double[] complex = new double[2];
- complex[0] = real;
- complex[1] = imaginary;
- return complex;
- }
- public double getReal() {
- return real;
- }
- public double getImaginary() {
- return imaginary;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement