Challenge
Assume two vectors \$\mathbf{a} = (a_1,a_2,\cdots,a_n)\$ and \$\mathbf{b} = (b_1,b_2,\cdots,b_n)\$ are given in an \$n\$-dimensional space, where at least one of \$b_1,\cdots,b_n\$ is nonzero. Then \$\mathbf{a}\$ can be uniquely decomposed into two vectors, one being a scalar multiple of \$\mathbf{b}\$ and one perpendicular to \$\mathbf{b}\$:
$$ \mathbf{a} = \mathbf{b}x + \mathbf{b^\perp}\text{, where }\mathbf{b^\perp} \cdot \mathbf{b}=0. $$
Given \$\mathbf{a}\$ and \$\mathbf{b}\$ as input, find the value of \$x\$.
This can be also thought of as the following: Imagine a line passing through the origin and the point \$\mathbf{b}\$. Then draw a perpendicular line on it that passes through the point \$\mathbf{a}\$, and denote the intersection \$\mathbf{c}\$. Finally, find the value of \$x\$ that satisfies \$\mathbf{c}=\mathbf{b}x\$.
You can use an explicit formula too (thanks to @xnor), which arises when calculating the projection:
$$ x=\frac{\mathbf{a} \cdot \mathbf{b}}{\mathbf{b} \cdot \mathbf{b}} $$
Standard code-golf rules apply. The shortest code in bytes wins.
Example
Here is an example in 2D space, where a=(2,7)
and b=(3,1)
. Observe that (2,7) = (3.9,1.3) + (-1.9,5.7)
where (3.9,1.3)
is equal to 1.3b
and (-1.9,5.7)
is perpendicular to b
. Therefore, the expected answer is 1.3
.
Test cases
a b answer
(2,7) (3,1) 1.3
(2,7) (-1,3) 1.9
(3,4,5) (0,0,1) 5
(3,4,5) (1,1,1) 4
(3,4,5) (1,-1,-1) -2
(3,4,5,6) (1,-2,1,2) 1.2