Skip to content

Instantly share code, notes, and snippets.

@jasonm23
Last active August 11, 2023 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonm23/eba3f2ff4545240961c2d673130ca2ad to your computer and use it in GitHub Desktop.
Save jasonm23/eba3f2ff4545240961c2d673130ca2ad to your computer and use it in GitHub Desktop.
Distance and angle between two cartesian points
#!/usr/bin/env python3
import math
import sys
def calculate_distance(x1, y1, x2, y2):
angle = calculate_angle(x1, y1, x2, y2)
return abs(y2 - y1) / math.sin(math.radians(angle))
def calculate_angle(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return math.degrees(math.atan2(dy, dx))
def print_point_info(x1, y1, x2, y2, label):
distance = calculate_distance(x1, y1, x2, y2)
angle = calculate_angle(x1, y1, x2, y2)
print(label)
print(f" Distance: {distance:.2f} units")
print(f" Angle : {angle:.2f} degrees")
print(f" : {math.radians(angle):.8f} radians")
if len(sys.argv) != 5:
print("Usage: pointdist x1 y1 x2 y2")
sys.exit(1)
x1, y1, x2, y2 = map(float, sys.argv[1:])
print_point_info(x1, y1, x2, y2, "Point A-B")
print_point_info(x2, y2, x1, y1, "Point B-A")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment