虚数
我有一个需要 3 个 double 并通过二次公式计算根的方法:
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 };
}
我想对此进行扩展并添加对虚数的支持。我将如何实现这个目标?我的第一个想法是,否则 if (discriminant < 0),我会得到判别式的绝对值并分解根式。我将把根输出给用户,所以不用担心 i,我有一个字符串解析器,它确切地知道将 i 放在哪里。关于更有效的方法有什么想法吗?
I have a method that takes 3 double
s and calculates the roots via the Quadratic Formula:
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 };
}
I want to expand on this and add support for imaginary numbers. How would I accomplish this? My first thought was, in else if (discriminant < 0)
, I would get the absolute value of the discriminant and factor the radical. I am going to output the roots to the user, so don't bother with the i, I have a String parser that knows exactly where to put the i. Any ideas on a more efficient method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您确实想继续处理复数/虚数,我建议实现一个表示复数的类。
可以在这里找到一个例子:
http://www.math.ksu.edu/~bennett/jomacg/c .html
如果你以某种方式构建双精度数、数组和字符串的混合计算,一段时间后它肯定会变得混乱。
If you really want to get going on Complex/Imaginary numbers I would suggest to implement a class that represents a complex number.
An example for that can be found here:
http://www.math.ksu.edu/~bennett/jomacg/c.html
If you somehow build your calculations of a mixture of doubles, arrays and strings it will definetely get messy after a while.