Reputation: 188
I feel as if this should be fairly straightforward but I have been staring at code and am now being stupid. I have a method that takes two input 3D vectors and returns the angle between them in degrees.
The method is as follows:
def CalculateAngleBetweenVector(vector, vector2):
dp = np.dot(vector, vector2)
maga = math.sqrt((vector[0] ** 2) + vector[1] ** 2 + vector[2] ** 2)
magb = math.sqrt((vector2[0] ** 2) + vector2[1] ** 2 + vector2[2] ** 2)
magc = maga * magb
dpmag = dp / magc
angleindeg = ((math.acos(dpmag)) * 180) / math.pi
return angleindeg
Currently I have two identical vectors going in to test something else and have realised this method errors when I do. The two vectors are:
[ 0.38154065 -0.38688849 -0.83949034]
The method I use fro working out the unit vectors for the inputs is:
UnitVector = Vector / np.linalg.norm(Vector)
Just incase something is wrong here.
Any and all help is much appreciated.
Thanks
edit:
sorry the vector going in is actually (0.38154065, -0.38688849, -0.83949034) I just copied the terminal print line. The error is a math domain error.
edit2:
Error traceback:
Traceback (most recent call last):
File "file path info that contains personal info Documents/com~apple~CloudDocs/WORK/Code1/CompareAnglesBetweenProteinAndMembane.py", line 261, in <module>
angle = CalculateAngleBetweenVector(ProteinRotatedUV, MemRotatedUV)
File "file path info that contains personal info Documents/com~apple~CloudDocs/WORK/Code1/CompareAnglesBetweenProteinAndMembane.py", line 167, in CalculateAngleBetweenVector
angleindeg = ((math.acos(dpmag)) * 180) / math.pi
ValueError: math domain error
Upvotes: 3
Views: 1181
Reputation: 25956
As discussed in comments, the problem stems from rounding errors in floating-point arithmetics (argument for acos
slightly out of range).
I would consider the following changes:
angle = acos(dot(A,B) / (|A|* |B|))
If the argument to the arccos is slightly above 1.0 or below -1.0, just round it. You don't need to do that if the argument is in range.
Normalization only helps if vectors are close to [0,0,0], or have very big entries - the calculation is more numerically stable. If neither is the case in your app, consider removing normalization.
Upvotes: 3