[英]How to solve imaginary quadratic roots in java?
我一直在嘗試很多,但它只顯示 NaN。 我不確定我是否做對了。
class Imaginary{
double a = 2;
double b = 3;
double c = 5;
double result = b * b - 4 * a * c;
if(result < 0.0){
double im1 = -2 + (Math.sqrt((result))/ 10);
double im2 = -2 - (Math.sqrt((result))/ 10);
System.out.println("x = " + imaginary1 + " or x = " + imaginary2);
}
}
你不應該使用 sqrt(result) 因為它總是會導致你取負數的平方根(這是你的結果條件)。 而是嘗試使用公式(例如完成正方形)。
希望它能回答你的問題:)
您需要在取平方根(取負數的平方根總是導致 NaN)和 append "i" 之前取負result
以使其為正。
double real = -b / (2*a);
double img = Math.sqrt(-result) / (2*a);
System.out.println("x = " + real + " + " + img +"i or x = " + real + " - " + img + "i");
由於您有一個復數根,因此您需要使用復數來求解方程。 Java 缺乏對復數的內置支持,但您可以例如使用Apache Commons :
if (result < 0.0) {
final Complex cb = new Complex(-b, 0.0);
final Complex root = new Complex(result, 0.0).sqrt();
final Complex r1 = cb.add(root).divide(2 * a);
final Complex r2 = cb.subtract(root).divide(2 * a);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.