Fix math domain errors in vector_angle

Wed, 24 Jan 2018 23:14:01 +0200

author
Santeri Piippo
date
Wed, 24 Jan 2018 23:14:01 +0200
changeset 31
02e7e1d73ebb
parent 30
0d9ca37901ed
child 32
75f44d3063da

Fix math domain errors in vector_angle

geometry.py file | annotate | diff | comparison | revisions
--- a/geometry.py	Tue Jan 23 15:30:48 2018 +0200
+++ b/geometry.py	Wed Jan 24 23:14:01 2018 +0200
@@ -393,6 +393,9 @@
         cosine /= vec_1.length() * vec_2.length()
     except ZeroDivisionError:
         return 0
+    # Fix the cosine, it can go outside bounds due to rounding errors,
+    # e.g. 1.0000000000000002, which then causes a math domain error.
+    cosine = min(max(-1, cosine), 1)
     angle = acos(cosine)
     if normalized and angle > π / 2:
         angle = π - angle

mercurial