-1

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

Elad Goldenberg
  • 99
  • 1
  • 10
  • 1
    This problem is more related to trigonometry than programming. You have to understand how the trigonometric functions work (in math, not Python). For example, you can't do calculate `acos` for a anything outside of the range `[-1, 1]` – DeepSpace May 14 '18 at 20:43
  • 2
    `(c**2 - a**2 - b**2)/-2*a*b` gives `-41690.0`. `acos` takes a value between `-1` and `1` – ktzr May 14 '18 at 20:45
  • In the future, please try to debug on your own. It took me less than a minute (and I'm sure that for @ktzr as well) to find the offending line and print the value that is being passed to `acos` – DeepSpace May 14 '18 at 20:48
  • @DeepSpace will do that next time – Elad Goldenberg May 14 '18 at 20:50

1 Answers1

1

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]
ktzr
  • 1,625
  • 1
  • 11
  • 25