To increase the speed at which I find the sine/cosine of an angle, I have built a reference table instead of calculating them on the fly. I have the same idea with finding the a
As angle(v1, v2) = acos( (v1x * v2x + v1y * v2y) / (sqrt(v1x^2+v1y^2) * sqrt(v2x^2+v2y^2)) ) and we know v2 = [1, 0]
var v = {x: 0, y: 1},
angleRad = Math.acos( v.x / Math.sqrt(v.x*v.x + v.y*v.y) ),
angleDeg = angleRad * 180 / Math.PI;
where v
is the vector [point2.x - point1.x , point2.y - point1.y]
Edit - I just realised you may have meant treat each point as a vector, in which case it'd be
var v1 = {x: 0, y: 1}, v2 = {x: 1, y: 0},
angleRad = Math.acos( (v1.x * v2.x + v1.y * v2.y) / ( Math.sqrt(v1.x*v1.x + v1.y*v1.y) * Math.sqrt(v2.x*v2.x + v2.y*v2.y) ) ),
angleDeg = angleRad * 180 / Math.PI;
where v1
is the vector [point1.x , point1.y]
and v2
is [point2.x , point2.y]
Edit 2
To speed up if you're using the vectors length many times, save it as e.g. v.length = ...
so you can get it without re-calculating again.
If you know every vector will need it's angles calculated multiple times, use the first method I wrote and cache it, i.e. v.angle = ...
. You can then you can do v2.angle - v1.angle
to find angle between the two, etc.
i.e. have
function Vector(x, y){
this.x = x;
this.y = y;
this.length = Math.sqrt(x*x + y*y);
this.angle = Math.acos( x / this.length );
}
jsperf of pre-computing and finding in an array of 3601
items vs using acos directly
That's definitely going to be smaller than a call to atan2
, since it's a square root and then a linear search through 3600 possibilities. Conversely many processors implement atan2 directly — it's FPATAN in Intel land.