Finding if a triangle is right-angled or not

回眸只為那壹抹淺笑 提交于 2019-12-11 17:04:15

问题


This Python 3 based function returns if a triangle is or isn't right-angled given side lengths x, y, and z. I'm having an issue simplifying the conditional statement. Should this function check for acute, right, obtuse, scalene, isosceles, and equilateral angles, or are there conditions I can skip? Any feedback is appreciated.

def right_angled(x, y, z):
    """This function returns if a triangle is or isn't
    right-angled given side lengths x, y, and z."""
    p = x + y + z #triangle perimeter
    a_sym = p / 180 #triangle perimeter divided by 180 
    one = x * a_sym #angle one
    two = y * a_sym #angle two
    three = z * a_sym #angle three
    if one and two or one and three or two and three == 90:
        return "The triangle is right-angled."
    elif one and two and three == 180:
        return "The triangle is right-angled." #next conditional(s)?
    else:
        return "The triangle is not right-angled."

print(right_angled(4, 5, 6))

回答1:


Your function is completely wrong.

You cannot find angle as ratio of a side and perimeter.

Expression if one and two does not calculate sum - and here is logical (boolean) operator.

To find whether rectangle is right, you can exploit Pythagorean theorem

def right_angled(a, b, c):
    if (a*a+b*b==c*c) or (c*c+b*b==a*a) or (a*a+c*c==b*b) :
        return "The triangle is right-angled." 
    else:
        return "The triangle is not right-angled."

Or just return boolean result

return (a*a+b*b==c*c) or (c*c+b*b==a*a) or (a*a+c*c==b*b)



回答2:


I suggest using the Pythagorean theorem to achieve this (a^2+b^2=c^2) by testing the 3 combinations of side lengths. To compensate for floating point imprecision, compare within a range:

def right_angled(a, b, c, e):
    return abs(a*a+b*b-c*c)<e or abs(b*b+c*c-a*a)<e or abs(c*c+a*a-b*b)<e

However, the range depends on the scale of the side lengths, i.e., small triangles pass the test more easily than big triangles. For example, any triangle with side length ~0.01 will pass the test if e=0.01. For this reason, it is safer (but more expensive) to normalize the side lengths using the formula (a^2+b^2)/c^2=1

def right_angled(a, b, c, e):
    return c>0 and abs(1-(a*a+b*b)/(c*c))<e or \
           a>0 and abs(1-(b*b+c*c)/(a*a))<e or \
           b>0 and abs(1-(c*c+a*a)/(b*b))<e


来源:https://stackoverflow.com/questions/56159486/finding-if-a-triangle-is-right-angled-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!