Q:

Why do I get ValueError : math domain error?

I wrote a function named analyze_the_shape that takes a list of 2D vertices such that the list is in the order of a clockwise traversal of the vertices in the 2D Euclidean space.
I call it in the interpreter and give [(0, 0), (0, 4.0), (4.0, 4.0), (4.0, 0)] as input but I get ValueError : math domain error. I expect to see return ["SQUARE", 4.0]. What can I do ?       
import math

def analyze_the_shape(liste):
    if len(liste) == 2 :
        d = ( (liste[1][0] - liste[0][0])**2 + (liste[1][1] - liste[0][1])**2 )**(0.5)   
        return ["LINESEGMENT", d ] 
    if len(liste) == 4 :
        d1 = abs(( (liste[1][0] - liste[0][0])**2 + (liste[1][1] - liste[0][1])**2 )**(0.5))
        d2 = abs(( (liste[2][0] - liste[1][0])**2 + (liste[2][1] - liste[1][1])**2 )**(0.5))
        d3 = abs(( (liste[3][0] - liste[2][0])**2 + (liste[3][1] - liste[2][1])**2 )**(0.5))
        d4 = abs(( (liste[0][0] - liste[3][0])**2 + (liste[0][1] - liste[3][1])**2 )**(0.5)) 
        hypo = abs(( (liste[2][1] - liste[0][1])**2 + (liste[2][0] - liste[0][0])**2 )**(0.5))
        cos_angle = float((hypo**2 - (d3)**2 + (d4)**2) / ((-2.0)*(d4)*(d3)))
        angle = math.degrees(math.acos(cos_angle))
        if d1 == d2 == d3 == d4 and abs(angle - 90.0) < 0.001 :
            return ["SQUARE", d1]  

This is the error I get:
>>> import a
>>> a.analyze_the_shape([(0, 0), (0, 4.0), (4.0, 4.0), (4.0, 0)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "a.py", line 15, in analyze_the_shape

ValueError: math domain error

A:

This exception means that cos_angle is not a valid parameter for math.acos.
Specifically, in this example, it is just below -1, which is out of acos definition.
You could probably try to force your returned cos_angle within [-1,1] with something like :
def clean_cos(cos_angle):
    return min(1,max(cos_angle,-1))

However, this will not return SQUARE, since cos_angle is more or less equals to -1 in your example, and angle thus equals 180. There is probably an issue with your computation before the exception.

