Search code examples
python-3.xmathunhandled-exception

math domain error in python when caluclating angles


trying to calculate all kind of triangle's angles by given sides. I have all the agorithms to do so, one slight problem is having a 'math domain error' which i can't find. Appreciate any help :)

from math import *
def angles(a, b, c):
    if a + b <= c or a + c <= b or c + b <= a:
        return [0, 0, 0]
    elif a == b == c:
        return [60,60,60]
    tempLst = []
    d = max(a,b,c) #To know which angle is the largest
    if a == d:
        if (b ** 2 + c ** 2) < d**2: #To know wether a triangle is an obtuse triangle
           tempLst.append(round(degrees(acos((c**2 - a**2 - b**2) / (-2 * c * b)))))
           tempLst.append(round(asin(a/sin(tempLst[0])*b)))
        else:    
           tempLst.append(round(degrees(asin(c/a))))
           tempLst.append(round(degrees(asin(b/a))))
    elif b == d:
        if (a**2+c**2) < d**2:
            tempLst.append(round(degrees(acos((c**2 - a**2 - b**2)/-2*c*a))))
            tempLst.append(round(asin(b/sin(tempLst[0])*a)))
        else: 
            tempLst.append(round(degrees(asin(c/b))))
            tempLst.append(round(degrees(asin(a/b))))
    else:
        if (b**2+a**2) < d**2:
            tempLst.append(round(degrees(acos((c**2 - a**2 - b**2)/-2*a*b))))
            tempLst.append(round(asin(c/sin(tempLst[0])*b)))
        else: 
            tempLst.append(round(degrees(asin(a/c))))
            tempLst.append(round(degrees(asin(b/c))))
    tempLst.append(180 - tempLst[0] - tempLst[1])
    return tempLst

Error: ValueError: math domain error

angles, 25

when trying to input these values: angles(11, 20, 30) ---> "Unhandled exception"

Thank you all


Solution

  • Your trig is off. Use the Law of Cosines

    from math import *
    
    
    def angles(a, b, c):
        if a + b <= c or a + c <= b or c + b <= a:
            return [0, 0, 0]
        elif a == b == c:
            return [60, 60, 60]
        tempLst = [
            round(degrees(acos((a ** 2 + b ** 2 - c ** 2) / (2 * a * b)))), # C
            round(degrees(acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)))), # A
            round(degrees(acos((c ** 2 + a ** 2 - b ** 2) / (2 * c * a))))  # B
        ]
    
        return tempLst
    
    
    print(angles(11, 20, 30))
    # -> [149, 11, 20]