S
S
Svyatoslav Khusamov2015-11-30 10:55:13
Mathematics
Svyatoslav Khusamov, 2015-11-30 10:55:13

How to write the correct formula for calculating the angle between vectors?

Hello! The problem is this. I have a formula for calculating the angle between vectors. It is standard:
cosf.gif
And now there are two vectors, the angle between which cannot be calculated in any way, since the right side of the equation is less than -1. These are the vectors:

var x1 = -0.045797169475341334, y1 = -0.9989507591808752;
var x2 = 0.04579716947534099, y2 = 0.9989507591808753;

As a result, the expression:
(x1 * x2 + y1 * y2) / Math.sqrt(Math.pow(x1, 2) + Math.pow(y1, 2)) * Math.sqrt(Math.pow(x2, 2) + Math.pow(y2, 2))

gives the result: -1.0000000000000002
And if we take the arccosine of this number, it will be NaN, which is understandable, since it is defined on the interval from -1 to 1.
How can I correct the formula so that this error does not occur?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
angru, 2015-11-30
@khusamov

var d = res < 0 ? Math.max(res, -1.0) : Math.min(res, 1.0);

S
southsoutheast, 2015-11-30
@southsoutheast

you have the module at the top missing.

G
GreatRash, 2015-11-30
@GreatRash

You think wrong .

var dot_product = x1 * y1 + x2 * y2;
var length_1 = Math.sqrt(x1 * x1 + y1 * y1);
var length_2 = Math.sqrt(x2 * x2 + y2 * y2);

var cos_a = dot_product / (length_1 * length_2);

E
Eugene, 2015-11-30
@Nc_Soft

You still think wrong
Must be

(x1 * x2 + y1 * y2) / Math.sqrt(Math.pow(x1, 2) + Math.pow(y1, 2)) / Math.sqrt(Math.pow(x2, 2) + Math.pow(y2, 2))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question