#! /usr/bin/python3 # ================================================================== # calculate the angle between two vectors (line segments) # based on: www.adamsmith.haus/python/answers/ # how-to-get-the-angle-between-two-vectors-in-python # ------------------------------------------------------------------- # Note: this code finds the smallest angle between two vectors. # it does not know clockwise/counterclockwise. # ------------------------------------------------------------------- # v1 - vector 1 # v2 - vector 2 # uv - display unit vectors (debug) # =================================================================== import numpy as np def two_vector_angle(v1,v2,uv=False): # ---- vector norm unit_v1 = v1 / np.linalg.norm(v1) unit_v2 = v2/np.linalg.norm(v2) if uv: print(f'unit_v1 = {unit_v1}') print(f'unit_v2 = {unit_v2}') #---- dot product of two vectors dot_product = np.dot(unit_v1, unit_v2) # --- generate the angle between v1 and v2 a_rad = np.arccos(dot_product) return a_rad # ------------------------------------------------------------------- # ---- main # ------------------------------------------------------------------- if __name__ == '__main__': # ---- Y axis v1 = (0.0,100.0) # Y axis # ---- simulated fold line vector deg = 30.0 rad = np.deg2rad(deg) v2 = [100.0 * np.cos(rad), 100.0 * np.sin(rad)] ang_rad = two_vector_angle(v1,v2) ang_deg = np.rad2deg(ang_rad) print(f'# test-deg={deg:3} ' + f'calc-rad={ang_rad:.3f} ' + f'calc-deg={ang_deg:.3f}')