Skip to content

Instantly share code, notes, and snippets.

@kylebutts
Created June 24, 2025 20:54
Show Gist options
  • Save kylebutts/3e123a376ed44efc90dd42b2e4438e84 to your computer and use it in GitHub Desktop.
Save kylebutts/3e123a376ed44efc90dd42b2e4438e84 to your computer and use it in GitHub Desktop.
Give three points of a triangle and get all angles and side lengths
triangle_info <- function(A, B, C) {
# Helper function to compute distance between two points
dist <- function(P, Q) sqrt((P[1] - Q[1])^2 + (P[2] - Q[2])^2)
# Side lengths
dist_AB <- dist(A, B)
dist_AC <- dist(A, C)
dist_BC <- dist(B, C)
# Law of Cosines for each angle
angle_A <- acos((dist_AB^2 + dist_AC^2 - dist_BC^2) / (2 * dist_AB * dist_AC)) * 180 / pi
angle_B <- acos((dist_AB^2 + dist_BC^2 - dist_AC^2) / (2 * dist_AB * dist_BC)) * 180 / pi
angle_C <- acos((dist_AC^2 + dist_BC^2 - dist_AB^2) / (2 * dist_AC * dist_BC)) * 180 / pi
return(list(
angle_A = angle_A,
angle_B = angle_B,
angle_C = angle_C,
dist_AB = dist_AB,
dist_AC = dist_AC,
dist_BC = dist_BC
))
}
# Example usage:
A <- c(0, 0)
B <- c(1, 0)
C <- c(0, 1)
triangle_info(A, B, C)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment