java 虚数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6959220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Imaginary numbers
提问by Mohit Deshpande
I have a method that takes 3 double
s and calculates the roots via the Quadratic Formula:
我有一个需要 3double
秒并通过二次公式计算根的方法:
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?
我想对此进行扩展并添加对虚数的支持。我将如何做到这一点?我的第一个想法是,在 中else if (discriminant < 0)
,我会得到判别式的绝对值并分解根数。我要将根输出给用户,所以不要打扰i,我有一个字符串解析器,它确切地知道将i放在哪里。关于更有效方法的任何想法?
回答by leifg
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
一个例子可以在这里找到: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.
如果您以某种方式构建双打、数组和字符串的混合计算,一段时间后它肯定会变得混乱。