在Java中求解方程的虛根實部和虛部可以使用復數(shù)類來實現(xiàn)。復數(shù)類的定義如下:
public class Complex { private double real; private double imaginary; public Complex(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } public double getReal() { return real; } public double getImaginary() { return imaginary; } public Complex add(Complex other) { double r = real + other.real; double i = imaginary + other.imaginary; return new Complex(r, i); } public Complex subtract(Complex other) { double r = real - other.real; double i = imaginary - other.imaginary; return new Complex(r, i); } public Complex multiply(Complex other) { double r = real * other.real - imaginary * other.imaginary; double i = real * other.imaginary + imaginary * other.real; return new Complex(r, i); } public Complex divide(Complex other) { double denominator = other.real * other.real + other.imaginary * other.imaginary; double r = (real * other.real + imaginary * other.imaginary) / denominator; double i = (imaginary * other.real - real * other.imaginary) / denominator; return new Complex(r, i); } public double abs() { return Math.sqrt(real * real + imaginary * imaginary); } public String toString() { return "(" + real + ", " + imaginary + ")"; } }
其中,real表示實部,imaginary表示虛部。接下來我們來求解方程的虛根實部和虛部的代碼:
public class EquationSolver { public static void main(String[] args) { Complex a = new Complex(2, 3); Complex b = new Complex(4, 5); Complex c = new Complex(6, 7); Complex delta = b.multiply(b).subtract(a.multiply(c).multiply(new Complex(4, 0))); if (delta.getReal() >= 0) { Complex x1 = b.add(delta.sqrt()).divide(a.multiply(new Complex(2, 0))); Complex x2 = b.subtract(delta.sqrt()).divide(a.multiply(new Complex(2, 0))); System.out.println("x1 = " + x1); System.out.println("x2 = " + x2); } else { Complex x1 = b.divide(a.multiply(new Complex(2, 0))); Complex x2 = new Complex(x1.getReal(), x1.getImaginary() + Math.sqrt(-1 * delta.getReal()) / a.abs()); Complex x3 = new Complex(x1.getReal(), x1.getImaginary() - Math.sqrt(-1 * delta.getReal()) / a.abs()); System.out.println("x1 = " + x1); System.out.println("x2 = " + x2); System.out.println("x3 = " + x3); } } }
通過上面的代碼我們可以求解出方程的虛根的實部和虛部。