私は3double
秒かかり、2次式を介して根を計算する方法を持っています:
public static double[] quadraticFormula(double a, double b, double c) throws ArithmeticException {
double root1 = 0;
double root2 = 0;
//sqrt(b^2 - 4ac)
double discriminant = (b * b) - (4 * a * c);
if (Double.isNaN(discriminant)) {
throw new ArithmeticException(discriminant + " is not a number!");
}
if (discriminant > 0) {
//Two roots
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
} else if (discriminant == 0) {
//One root
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
} else if (discriminant < 0) {
//Imaginary roots
}
return new double[] { root1, root2 };
}
これを拡張して、虚数のサポートを追加したいと思います。どうすればこれを達成できますか? 私が最初に考えたのは、 ではelse if (discriminant < 0)
、判別式の絶対値を取得し、基数を因数分解するということでした。ルートをユーザーに出力するので、 iを気にしないでください。 iをどこに置くかを正確に知っている String パーサーがあります。より効率的な方法に関するアイデアはありますか?