2013-11-25 42 views
1

我試圖讓Python中的計算器,但我發現錯用餘弦定律我已經把英寸的Python 3.3側餘弦定律計算器錯誤

這是我

x = float(input("First Side ")) 
y = float(input("Second Side ")) 
z = float(input("Angle which isn't opposite First or Second Side ")) 
print (" ") 
print ("Side is: "+str(math.sqrt(((x**2)+(y**2))-(2*x*y*(math.cos(z)*(180/math.pi)))))) 

這是我的錯誤

Traceback (most recent call last): 
    File "D:/Users/---------/Python/test calc.py", line 339, in <module> 
    print ("Side is: "+str(math.sqrt(((x**2)+(y**2))-(2*x*y*(math.cos(z)*(180/math.pi)))))) 
ValueError: math domain error 

你做這個工作了餘弦定律:

a=√(b^2+c^2−2*b*c*cos(α)) 

在我做了什麼

x=b 
y=c 
z=α 

回答

2
在該行

2*x*y*(math.cos(z)*(180/math.pi)) 

你似乎在試圖轉換從度弧度

?但是(1)因素是倒置的,(2)它需要在cos(...)之內。

所以你可能意味着

2*x*y*math.cos(z*math.pi/180) 

(檢查:當z爲180度時,上面的代碼給出PI弧度)。

2

這對我的作品;我想象你正在輸入三角形不可能的數字。在普通計算器中試試你的輸入,看看它是否有效。

此外,請注意您的角度需要以弧度(或您需要將其轉換爲度數)。

我嘗試的3,4和3.14/2(約90弧度度),並得到4.99,這近似於5.

+0

哦,公平的說,我使用Python 2.7。以防萬一。 – thumbtackthief

1

正確答案看來側面math.cos(Z)*(180/math.pi)是錯誤的部分,使math.sqrt內部的某些情況爲負。

print ("Side is: "+str(math.sqrt(((x**2)+(y**2))-(2*x*y*math.cos(z))))) 

math.cos(z*math.pi/180)將是你想要的。

(編輯:修正顛倒分數感謝:安德魯·庫克))

+0

我認爲這是倒過來。它希望是pi/180,而不是180/pi。考慮角度180度。這應該給出pi弧度的值。 –