Calculating angle between two vectors?

旧时模样 提交于 2019-12-04 19:25:11

If I see it correctly, the formula

angle = atan2(x, -y) * 180.0/M_PI;

should work in all quadrants, making all the if statements unnecessary.


atan2(y, x) returns the angle between the vector (x, y) and the positive x-axis, the return value is always between -pi and pi.

Replacing (y, x) by (x, -y) in the arguments means that the vector is rotated by 90 degrees, therefore the result of the above formula is the angle measured to the negative y-axis, which is what you wanted.


Update (according to "edit2" in the question): If the requirement is "south = 0 deg", "east = -90 deg", "west = +90 deg" then the formula would be

angle = atan2(-x, -y) * 180.0/M_PI;

The atan2 function already takes quadrant into account. In other words, it "knows" that you're in the third quadrant if both x and y are negative. Knowing that, you can see what the angle output for atan2(y, x) is, and then change it to how you want it displayed.

The main reason why Google maps works even with a relatively inaccurate compass is that the structures of the roads give you hints, so you can get by with a bigger error than if you didn't know where the roads were.

Actually, after deciding what quadrant it is I changed code to always calculate atan2 with positive values of x and y - now it works!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!