[SWIFT] Find the angle between two vectors

Commentary

If the angle formed by the vector $ \ vec {a} = (a_1, a_2), \ vec {b} = (b_1, b_2) $ that is not $ \ vec {0} $ is $ \ theta $, the following holds.

\begin{align}
\cos\theta &= \frac{\vec{a}\cdot\vec{b}}{|\vec{a}||\vec{b}|} \\
&=\frac{a_1 b_1 + a_2 b_2}{\sqrt{a_1^2 + a_2^2}\sqrt{b_1^2 + b_2^2}}
\end{align}

If the inverse cosine (arc cosine) of cos $ \ theta $ obtained here is obtained, $ \ theta $ can be obtained.

code

func angleBetween(_ vec1: simd_float3, and vec2: simd_float3) -> Float {
   let cosT = (vec1.x * vec2.x + vec1.z * vec2.z) / (sqrt(pow(vec1.x, 2) +
              pow(vec1.z, 2)) * sqrt(pow(vec2.x, 2) + pow(vec2.z, 2)))
   let deg = acos(cosT) * 180 / Float.pi
   return deg
}
let v1 = simd_float3(20, 0, 20)
let v2 = simd_float3(0, 0, 20)
let angle = angleBetween(v1, and: v2)

print(angle) //45 degrees

Recommended Posts

Find the angle between two vectors
How to find the distance and angle between two points on a plane
Find the difference between List types
How to find the average angle
Calculate the latitude / longitude distance between two points
Difference between Java and JavaScript (how to find the average)
Output the difference between each field of two objects in Java
[Android, Java] Method to find the elapsed date from two dates