Learn R Programming

clugenr (version 1.0.4)

angle_btw: Angle between two n-dimensional vectors.

Description

Typically, the angle between two vectors v1 and v2 can be obtained with:

acos((v1 %*% v2) / (norm(v1, "2") * norm(v2, "2")))

However, this approach is numerically unstable. The version provided here is numerically stable and based on the Angle Between Vectors Julia package by Jeffrey Sarnoff (MIT license), implementing an algorithm provided by Prof. W. Kahan in these notes (see page 15).

Usage

angle_btw(v1, v2)

Value

Angle between v1 and v2 in radians.

Arguments

v1

First vector.

v2

Second vector.

Examples

Run this code
angle_btw(c(1.0, 1.0, 1.0, 1.0), c(1.0, 0.0, 0.0, 0.0)) * 180 / pi

Run the code above in your browser using DataLab