Dot Product

From Graal Bible

The Dot Product is a property of vectors. It is defined as the sum of the products of each component of a vector. This is a useful property when trying to determine the angle between two vectors in n-dimensions.

Definition

The dot product of vectors u and v is written u•v and is pronounced "u dot v". This should not be confused with the multiplication dot (below marked as · as opposed to •)
The dot product simply returns a number. This number is the sum of products of each component of the vector. So, if we have vectors u = <3,5,7> and v = <9,4,2>, the dot product would be

u&#149;v = <3,5,7>&#149;<9,4,2> = 3·9 + 5·4 + 7·2 = 61

This value has special meaning with vectors. It can also be calculated by the magnitude of u multiplied by the magnitude of v multiplied by the cosine of the angle between them.

|u||v|cos(θ)

Deriving the Dot Product

The dot product was merely derived from the law of cosines:

c2 = a2 + b2 - 2 · a · b · cos(θ)

Imagine a triangle with three points, A, B, and C and we are trying to find the size of angle ∠BAC. In this triangle, AB = c, AC = b, and BC = a. Thus, we have

(AB)2 = (BC)2 + (AC)2 - 2 · (BC) · (AC) · cos(θ)
(AB)2 - (BC)2 - (AC)2 = -2 · (BC) · (AC) · cos(θ)
[(AB)2 - (BC)2 - (AC)2] / [-2 · (BC) · (AC)] = cos(θ)
[-(AB)2 + (BC)2 + (AC)2] / [2 · (BC) · (AC)] = cos(θ)

At this point, we replace all sides with vectors. BC = |u|, AC = |v|, AB = |u-v|.

[-|u-v|2 + |u|2 + |v|2] / [2 · |u| · |v|] = cos(θ)
[-[(u12 - 2·u1·v1 + v12) + (u22 - 2·u2·v2 + v22) + (u32 - 2·u3·v3 + v13)] + u12 + u22 + u32 + v12 + v22 + v32] / [2·|u|·|v|] = cos(θ)

This calculation is done by "multiplying" the two vectors together. In reality, |u|2 = u&#149;u, so it is merely following the definition of the dot product above.

[-(-2·u1·v1 - 2·u2·v2 - 2·u3·v3)] / [2·|u|·|v|] = cos(θ)
[2·u1·v1 + 2·u2·v2 + 2·u3·v3)] / [2·|u|·|v|] = cos(θ)
[u1·v1 + u2·v2 + u3·v3)] / [|u|·|v|] = cos(θ)

And since

u1·v1 + u2·v2 + u3·v3 = u&#149;v

We have then

u&#149;v/[|u||v|] = cos(θ)
u&#149;v = |u||v|cos(θ)

The Dot Product in GraalScript

The dot product is a function of vectors in format {x,y,z}. It returns a float, as it should. This function in GraalScript is vectordot(u,v). It's return value is just simply xuxv + yuyv + zuzv.