Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

python numpy function to calc angle betweent two vectors

  1. User

    python numpy function to calc angle betweent two vectors

  2. Assistant

    You can use the numpy library to calculate the angle between two vectors. Here's a function that does this using the dot product and arccosine:

    import numpy as np
    
    def angle_between_vectors(v1, v2):
        # Normalize the input vectors
        v1_normalized = v1 / np.linalg.norm(v1)
        v2_normalized = v2 / np.linalg.norm(v2)
        
        # Compute the dot product of the normalized vectors
        dot_product = np.dot(v1_normalized, v2_normalized)
        
        # Clip the dot product value to avoid any floating-point inaccuracies
        dot_product = np.clip(dot_product, -1.0, 1.0)
        
        # Calculate the angle using the arccosine function, and convert it to degrees
        angle_rad = np.arccos(dot_product)
        angle_deg = np.degrees(angle_rad)
        
        return angle_deg
    
    # Example usage:
    v1 = np.array([1, 0, 0])
    v2 = np.array([0, 1, 0])
    
    angle = angle_between_vectors(v1, v2)
    print("Angle between vectors:", angle, "degrees")
    

    This will give you the angle between two vectors in degrees. You can easily modify this to return the result in radians if required.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.