Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently calculate cotangents from vectors

I'm trying to implement a function to compute the cotangents of vectors (the mathematical ones) via the standard formula:

cot(a, b) = (a * b) / |a x b|, where a and b are vectors

A colleague told me that calculating 1/|a x b| is not the best thing to give a computer to calculate. Another alternative coming to my head is first calculating the angle and than using cotan functions for radians angles.

What would be the method of choice here? (Is there maybe another one, other than the mentioned ones)

like image 824
martin.zaenker Avatar asked Sep 27 '22 11:09

martin.zaenker


1 Answers

You probably want to take the cotangent of the angle between two vectors.

You can indeed first compute the angle with

Angle= atan(cross / dot) 

or better

Angle= atan2(cross, dot)

This angle can also be obtained as the difference of the directions of the two vectors

Angle= atan2(by, bx) - atan2(ay, ax)

Then take the cotangent

1. / tan(Angle)

or the tangent of the complementary angle

tan(atan2(dot, cross))

Anyway, think that this involves the evaluation of two or three transcendental functions, which is costly and less accurate.

From the third equation above, you can derive

cotan(Angle)= (1 + by/bx.ay/ax) / (by/bx - ay/ax)

This is just a rewrite of your initial formula, but more costly (3 divisions) and that can fail for more angles.

So

(ax bx + ay by) / (ax by - ay bx)

is definitely the faster and safer approach.

Unless there are special circumstances like low accuracy being enough, other expressions being computed at the same time or conditions on the vectors, I don't see a better way.

like image 88
Yves Daoust Avatar answered Nov 15 '22 08:11

Yves Daoust