2010-11-08 66 views
3

我已經構建了一個非常簡單但功能完備並且相當有用的WinForms C#應用程序,它可以解決二次方程的實根。C#應用程序求解二次虛根

這是我的當前編程邏輯:

string noDivideByZero = "Enter an a value that isn't 0"; 
    txtSolution1.Text = noDivideByZero; 
    txtSolution2.Text = noDivideByZero; 

    decimal aValue = nmcA.Value; 
    decimal bValue = nmcB.Value; 
    decimal cValue = nmcC.Value; 

    decimal solution1, solution2; 
    string solution1String, solution2String; 

    //Quadratic Formula: x = (-b +- sqrt(b^2 - 4ac))/2a 

    //Calculate discriminant 
    decimal insideSquareRoot = (bValue * bValue) - 4 * aValue * cValue; 

    if (insideSquareRoot < 0) 
    { 
     //No real solution 
     solution1String = "No real solutions!"; 
     solution2String = "No real solutions!"; 

     txtSolution1.Text = solution1String; 
     txtSolution2.Text = solution2String; 
    } 
    else if (insideSquareRoot == 0) 
    { 
     //One real solution 
     decimal sqrtOneSolution = (decimal)Math.Sqrt((double)insideSquareRoot); 
     solution1 = (-bValue + sqrtOneSolution)/(2 * aValue); 
     solution2String = "No real solution!"; 

     txtSolution1.Text = solution1.ToString(); 
     txtSolution2.Text = solution2String; 
    } 
    else if (insideSquareRoot > 0) 
    { 
     //Two real solutions 
     decimal sqrtTwoSolutions = (decimal)Math.Sqrt((double)insideSquareRoot); 
     solution1 = (-bValue + sqrtTwoSolutions)/(2 * aValue); 
     solution2 = (-bValue - sqrtTwoSolutions)/(2 * aValue); 

     txtSolution1.Text = solution1.ToString(); 
     txtSolution2.Text = solution2.ToString(); 
    } 

txtSolution1txtSolution2是未允許接收輸入的文本框,但輸出的計算結果

nmcAnmcBnmcC是用於由最終用戶輸入的a,b和c值的NumericUpDown控件

好的,所以我希望能夠採取一步進一步,並可能解決假想的價值。考慮到我已經建立了條件,只有當判別等於0或小於0時,我才需要考慮虛數值。

但是,我想不出一個好辦法來解決這個問題。當一個人試圖取一個負數的平方根時,就會出現複雜的解,導致出現在任何地方。 i = sqroot(-1)i^2 = -1

有誰知道如何解決這個問題,或者如果它只是不值得的時間?

編輯

隨着多一點谷歌搜索,我發現有可能與C#4.0(或.NET 4.0,我不知道哪)有內置的複數支持System.Numerics.Complex。我現在正在檢查這個。

+1

我不知道你爲什麼將所有內容都轉換爲十進制數,並且你沒有明顯的原因取得零的平方根(它總是零並且對答案沒有任何貢獻),在這種情況下,'solution2String'應該是「重複根」,而不是「沒有真正的解」。 – 2010-11-08 23:04:03

+0

哎呀,我忘了重複的根,它應該說'多重性0',而不是,或類似的東西。感謝您指出了這一點!另外,十進制給出更高的準確性,不是嗎? – Qcom 2010-11-08 23:05:57

+2

你正在做'double'的數學,然後轉換成'decimal'。所以不,你沒有得到更高的準確性,你只是放慢了工作。 – 2010-11-08 23:19:01

回答

0

那麼你認爲你可能有什麼問題? 您已在檢查想象結果。只需相應計算 - 例如。執行平方根,但具有正值,並跟蹤真實和想象的部分。

4

例如您要計算

(-b + sqrt(inside))/(2*a) 

Math.Sqrt不知道虛數,所以如果嘎嘎叫着inside < 0。但是我們總是可以在不改變答案的情況下乘以1。請注意,我 = -1。和-1 *我 = 1,所以,讓我們乘以-1 *我和簡化:

(-b + sqrt(inside * -1 * i**2))/(2*a) 
(-b + sqrt(-inside) * sqrt(i**2))/(2*a) 
(-b + sqrt(-inside) * i)/(2*a) 
-b/(2*a) + sqrt(-inside)/(2*a) * i 

所以下面的C#代碼:

solution1String = (-b/(2*a)).ToString() + 
         " + " + (Math.Sqrt(-inside)/(2*a)).ToString() + " i";