1
votes

I am trying to get the angle between three points on a plane using this formula:

cos-1((P122 + P132 - P232)/(2 * P12 * P13))

but occasionally I am getting a math domain exception. here is the function:

P12 = math.sqrt((x1-x2)**2 + (y1-y2)**2)
P13 = math.sqrt((x1-x3)**2 + (y1-y3)**2)
P23 = math.sqrt((x2-x3)**2 + (y2-y3)**2)

if P12 ==0 or P23 ==0 or P13 ==0 :
    return 0
return math.acos((P12**2 + P13**2 - P23**2) / (2*P12*P13) )

where P1 is the vertex what could be going wrong here?

Thanks

1
occasionally I am getting a math domain exception Do you mean something like on Sundays before noon or something like when the inputs have these characteristics ... ?High Performance Mark
@HighPerformanceMark - well.. I dont have the specific inputs that produced this behavior. As it only happens once in every couple of thousands of times the function is called. I added a try except block to print those, and will post it up when I have them, but it could be a while.WeaselFox

1 Answers

2
votes

You will sometimes get this error when the points are co-linear (or possibly very close to co-linear)

eg

(-1,-1),(1,1),(100,100)

gives

P12 = 140.007142675 
P13 = 2.82842712475
P23 = 142.8355698

and

>>> (P12**2 + P13**2 - P23**2) / (2*P12*P13)
-1.0000000000901725

It's due to floating point errors and you'll end up passing a number slightly larger than 1 or slightly smaller than -1 to acos