![](/img/trans.png)
[英]Why is the square root of a negative number not purely imaginary in Python?
[英]turn negative number to imaginary
我正在制作一個可以計算二次方程式分辨率的程序。 當判別式d
為非負數時有效,但對於復數根而言則無效。
如何插入假想的平方根?
import math
a = input("insert the value of a: ")
b = input("insert the value of b: ")
c = input("insert the value of c: ")
def d(a,b,c) : return (b**2)-(4.*a*c)
def x1(d,a,b,c) : return (b-(2.*b))+(math.sqrt ( d ))/2.*a
def x2(d,a,b,c) : return (b-(2.*b))-(math.sqrt ( d ))/2.*a
print ("the values of D,X' e X'' respectively: ")
print (d(a,b,c),x1(d,a,b,c),x2(d,a,b,c))
另外,當我使用a=4 b=4 c=1
且d
將為0
,出現以下錯誤。 我不確定這是怎么回事。
Traceback (most recent call last):
File "H:/Python27/equation2.py", line 9, in <module>
print (d(a,b,c),x1(d,a,b,c),x2(d,a,b,c))
File "H:/Python27/equation2.py", line 6, in x1
def x1(d,a,b,c) : return (b-(2.*b))+(math.sqrt ( d ))/2.*a
TypeError: a float is required
您正在嘗試使用某個函數的sqrt。 函數名稱不會自動表示最近調用的結果。 嘗試一個臨時變量:
d_result = d(a,b,c)
print (d_result, x1(d_result,a,b,c), x2(d_result,a,b,c))
這僅修復了致命錯誤; 當前的問題仍然是您不處理復雜的根。 注意:對於您給定的a = b = c = 4的情況,判據為-48, 而不是 0,如您的過帳狀態所示。
在這里,您有兩門課程:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.