I am trying to calculate the angle between some vectors in python2.7. I am using the following identity to find the angle.
theta = acos(v . w / |v||w|)
For a particular instance my code is:
v = numpy.array([1.0, 1.0, 1.0])
w = numpy.array([1.0, 1.0, 1.0])
a = numpy.dot(v, w) / (numpy.linalg.norm(v) * numpy.linalg.norm(w))
theta = math.acos(a)
When I run this I get the error ValueError: math domain error
I assume this is because acos is only defined on the domain [-1,1] and my value 'a' is a float which is very close to 1 but actually a little bit bigger. I can confirm this with print Decimal(a)
and I get 1.0000000000000002220446...
What is the best way to work around this problem?
All I can think of is to check for any values of 'a' being bigger than 1 (or less than -1) and round them to precisely 1. This seems like a tacky work around. Is there a neater / more conventional way to solve this problem?