関連 http://qiita.com/7of9/items/dd241297a7231485767d
あるベクトルと別のベクトルの間の角度を計算する。
角度はclockwise方向をとる。
以下にpython実装がある。
http://stackoverflow.com/questions/31735499/calculate-angle-clockwise-between-two-points
determinantが出てくる。2x2の場合はad-bc。3x3の場合はサラスの公式を使う。
http://www.mathsisfun.com/algebra/matrix-determinant.html
上記のpython実装を自分が必要としているC実装にした。 namingはかなり適当。
# include <stdio.h>
# include <math.h>
float get_length(float vs[2])
{
return sqrt( pow(vs[0],2) + pow(vs[1],2) );
}
float get_dot_product(float vs[2], float ws[2])
{
return vs[0]*ws[0] + vs[1]*ws[1];
}
float get_determinant(float vs[2], float ws[2])
{
return vs[0]*ws[1] - vs[1]*ws[0];
}
float get_inner_product(float vs[2], float ws[2])
{
float cosx = get_dot_product(vs,ws);
cosx = cosx / (get_length(vs) * get_length(ws));
float rad = acos(cosx);
return rad * 180.0 / acos(-1.0);
}
float get_angle_clockwise(float As[2], float Bs[2])
{
float inner = get_inner_product(As, Bs);
float det = get_determinant(As, Bs);
if (det < 0.0) {
return inner;
} else {
return 360.0 - inner;
}
}
float get_angle_clockwise_wrapper(float x1, float x2, float y1, float y2)
{
float Xs[2];
float Ys[2];
Xs[0] = x1;
Xs[1] = x2;
Ys[0] = y1;
Ys[1] = y2;
return get_angle_clockwise(Xs, Ys);
}
int main(void) {
printf("%f \n", get_angle_clockwise_wrapper(0,1, 1,0));
printf("%f \n", get_angle_clockwise_wrapper(1,0, 0,1));
printf("%f \n", get_angle_clockwise_wrapper(0,1, 1,1));
return 0;
}
結果
Success time: 0 memory: 2156 signal:0
90.000000
270.000000
45.000000
上記のpython実装(とそれに基づくC実装)では2つのベクトルが重なる場合は角度は0度でなく360度になる
このあたりは適宜修正が必要。