Python中的错误处理np.arccos()和三角形分类



下面的代码是我尝试的代码大战挑战,要求您计算三角形的内角。真的很不优雅,蛮力。我通过了所有的测试用例,但也收到一个错误:

-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。

输入参数是给定三角形的边。所有输入值为非负浮点数或整数(或两者兼而有之)。

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个其他测试我看不到。

您需要检查传递给numpy.arccos的值。它们必须在-1到1之间。但由于浮点运算,它们最终可能大于1或小于-1。

最新更新