Roka545
Roka545

Reputation: 3626

How to calculate vector direction between two vectors on a grid given a single value for X and Y

I have two values on a Cartesian grid (max value is 1).

For the X point, the value is 0.5. So the vector would point straight up from (0,0) to (0, 0.5). For the Y point, the value is 0.5. So the vector would point to the right from (0,0) to (0.5, 0)

So, the angle between the two vector should be 135 degrees (assuming you count degrees on the grid clockwise with 0 starting at the far left).

So, given that information, how would one calculate the angle between those two vectors?

enter image description here

Upvotes: 1

Views: 4401

Answers (3)

Stef
Stef

Reputation: 15504

Call u = (ux, uy) and v = (vx, vy) your two vectors.

First step: find the direction of the vector "between u and v". If u and v had same norm, we could just pick their sum. So, first, normalize u and v, then add them:

w        = u * norm(v) + v * norm(u)
(wx, wy) = (ux * norm(v) + vx * norm(u), uy * norm(v) + vy * norm(u))

Then, use atan2 to find the angle corresponding to w. There are 8 different conventions to use atan2, and you said that you wanted the west-clockwise convention:

angle_radians = atan2(wy, -wx)

Then, since you wanted to express the angle in degrees rather than in radians, convert the units:

angle_degrees = angle_radians * 180 / pi.

Testing in python:

import math

ux, uy = u = (0, 0.5)
vx, vy = v = (0.6, 0)

normu = math.hypot(ux,uy)
normv = math.hypot(vx,vy)

(wx, wy) = w = (uc * normv + vc * normu for uc,vc in zip(u,v))

angle_radians = math.atan2(wy, -wx)
angle_degrees = angle_radians * 180 / math.pi

print(angle_degrees)
# 135.0

Upvotes: 1

Mike Dunlavey
Mike Dunlavey

Reputation: 40649

Use arctangent. Then if the angle is outside the range you want, add or subtract 2pi.

Upvotes: 1

Alexis Olson
Alexis Olson

Reputation: 40204

The if your point is (x,y), then arctan(y/x) gives you the angle from the right axis to your point in the counterclockwise direction. Since you want the value from the left axis in the clockwise direction, try 180 - arctan(y/x). (Be sure you convert the arctan result to degrees!)

Upvotes: 1

Related Questions