Code Example: angle_between_two_vectors.py

#! /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
# -------------------------------------------------------------------
#
# -----------------unit_v1=[0. 1.0]
#
# -----------------unit_v2=[ 1.000, 0.000]
# test-deg=  0 calc-rad=1.571 calc-deg=90.000
#
# -----------------unit_v2=[ 0.707, 0.707]
# test-deg= 45 calc-rad=0.785 calc-deg=45.000
#
# -----------------unit_v2=[ 0.000, 1.000]
# test-deg= 90 calc-rad=0.000 calc-deg=0.000
#
# -----------------unit_v2=[-0.707, 0.707]
# test-deg=135 calc-rad=0.785 calc-deg=45.000
#
# -----------------unit_v2=[-1.000, 0.000]
# test-deg=180 calc-rad=1.571 calc-deg=90.000
#
# -----------------unit_v2=[-0.707,-0.707]
# test-deg=225 calc-rad=2.356 calc-deg=135.000
#
# -----------------unit_v2=[-0.000,-1.000]
# test-deg=270 calc-rad=3.142 calc-deg=180.000
#
# -----------------unit_v2=[ 0.707,-0.707]
# test-deg=315 calc-rad=2.356 calc-deg=135.000
#
# -----------------unit_v2=[ 1.000,-0.000]
# test-deg=360 calc-rad=1.571 calc-deg=90.000
#
# ===================================================================

import numpy as np

v1 = (0.0,100.0)           # Y axis

unit_v1 = v1 / np.linalg.norm(v1)

print()
print(f'-----------------unit_v1={unit_v1}')

for deg in range(0,361,45):

    print()

    rad = np.deg2rad(float(deg))

    v2 = [100.0 * np.cos(rad), 100.0 * np.sin(rad)]

    ##print(f'--v2-------------{type(v2)}')
    ##print(f'--v2-------------[{v2[0]:6.3f},{v2[1]:6.3f}]')

    unit_v2 = v2/np.linalg.norm(v2)

    print(f'-----------------unit_v2=' +
          f'[{unit_v2[0]:6.3f},{unit_v2[1]:6.3f}]')

    dot_product = np.dot(unit_v1, unit_v2)

    a_rad = np.arccos(dot_product)

    ##print(f'------------------{type(a_rad)}')
    ##print(f'------------------{a_rad}')

    a_deg = np.rad2deg(a_rad)

    print(f'test-deg={deg:3} ',end='')
    print(f'calc-rad={a_rad:.3f} ',end='')
    print(f'calc-deg={a_deg:.3f}')