2016-09-30 250 views
0

下面的代碼是我在codewars挑戰的嘗試,要求你calculate the interior angles of a triangle。真正不雅,蠻力。我通過了所有的測試案例,而且還收到了一個錯誤:錯誤處理np.arccos()和Python中的三角形分類

-c:37: RuntimeWarning: invalid value encountered in arccos 
-c:38: RuntimeWarning: invalid value encountered in arccos 
-c:39: RuntimeWarning: invalid value encountered in arccos 

所以我試圖找出如何我目前的檢查不要再追伽瑪計算之前無效值(地指出**在代碼,如下)。

該問題:

你應該計算三角形的類型具有三個給定邊a,b和c(以任何順序給出)。

如果所有角度都小於90°,​​這是三角形急性和功能應該返回1.

如果一個角是嚴格90°,這個三角形是正確的,功能應該返回2.

如果一個角度大於90°,​​這個三角形是鈍角和功能應該返回3.

如果三個側面不能形成三角形,或一個角度爲180°(這將會三角形成段) - 函數應該返回0

輸入參數ers是給定三角形的邊。所有輸入值都是非負浮點數或整數(或兩者)。

import numpy 
def triangle_type(a, b, c): 
    # Should return triangle type: 
    # 0 : if triangle cannot be made with given sides 
    # 1 : acute triangle 
    # 2 : right triangle 
    # 3 : obtuse triangle 

    # make sure all sides are non-zero 
    if a and b and c: 
     pass 
    else: 
     return 0 

    # triangle inequality test 
    if not ((c - b) < a < (c + b)) and ((a - c) < b < (a + c)) and ((b - a) < b < (b + a)): 
     return 0 
    elif a < b < c or b < a < c: 
     # print a,b,c 
     pass 
    elif b < c < a or c < b < a: 
     a, c = c, a 
     # print a, b, c 
    elif c < a < b or a < c < b: 
     b, c = c, b 
     # print a, b, c 
    else: 
     # print a, b, c 
     pass 

    # calculate the gammas **THIS IS WHERE I NEED HELD** 
    gamma_1 = numpy.rad2deg(numpy.arccos((a * a + b * b - c * c)/(2.0 * a * b))) 
    gamma_2 = numpy.rad2deg(numpy.arccos((c * c + a * a - b * b)/(2.0 * c * a))) 
    gamma_3 = numpy.rad2deg(numpy.arccos((b * b + c * c - a * a)/(2.0 * b * c))) 

    #check for a right angle 
    if (a * a + b * b == c * c) or (b * b + c * c == a * a) or (c * c + b * b == a * a): 
     return 2 
    #check acute angles 
    elif max(gamma_1, gamma_2, gamma_3) < 90.0: 
     return 1 
    #check obtuse 
    elif max(gamma_1, gamma_2, gamma_3) > 90.0: 
     return 3 
    else: 
     return 0 

我無法檢查gamma值的有效性,而不實際進行調用,從而產生錯誤。我怎樣才能解決這個問題?

一些測試用例

triangle_type(7,3,2) # Not triangle 0 
triangle_type(2,4,6) # Not triangle 0 
triangle_type(8,5,7) # Acute 1 
triangle_type(3,4,5) # Right 2 
triangle_type(7,12,8) # Obtuse 3 

但是,這絕不是詳盡的 - 有121次其他的測試中,我看不到。

回答

0

您需要檢查您傳遞給numpy.arccos的值。它們必須介於-1和1之間。但是由於浮點計算,它們可能會大於1或小於-1。