Implementing Vectors in Python
Swipe to show menu
Defining Vectors in Python
In Python, we use NumPy arrays to define 2D vectors like this:
1234567import numpy as np v1 = np.array([2, 1]) v2 = np.array([1, 3]) print(f'v1 = {v1}') print(f'v2 = {v2}')
These represent the vectors:
v1β=(2,1),v2β=(1,3)These can now be added, subtracted, or used in dot product and magnitude calculations.
Vector Addition
To compute vector addition:
1234567import numpy as np v1 = np.array([2, 1]) v2 = np.array([1, 3]) v3 = v1 + v2 print(f'v3 = v1 + v2 = {v3}')
This performs:
(2,1)+(1,3)=(3,4)This matches the rule for vector addition:
a+b=(a1β+b1β,a2β+b2β)Vector Magnitude (Length)
To calculate magnitude in Python:
np.linalg.norm(v)
For vector [3, 4]:
123import numpy as np print(np.linalg.norm([3, 4])) # 5.0
This uses the formula:
β£aβ£=a12β+a22ββDot Product
To calculate the dot product:
123import numpy as np print(np.dot([1, 2], [2, 3]))
Which gives:
[1,2]β [2,3]=1β 2+2β 3=8Dot product general rule:
aβ b=a1βb1β+a2βb2βVisualizing Vectors with Matplotlib
You can use the quiver() function in Matplotlib to draw arrows representing vectors and their resultant. Each arrow shows the position, direction, and magnitude of a vector.
- Blue: v1β, drawn from the origin;
- Green: v2β, starting at the head of v1β;
- Red: resultant vector, drawn from the origin to the final tip.
Example:
123456789101112131415161718import matplotlib.pyplot as plt fig, ax = plt.subplots() # v1 ax.quiver(0, 0, 2, 1, color='blue', angles='xy', scale_units='xy', scale=1) # v2 (head-to-tail) ax.quiver(2, 1, 1, 3, color='green', angles='xy', scale_units='xy', scale=1) # resultant ax.quiver(0, 0, 3, 4, color='red', angles='xy', scale_units='xy', scale=1) plt.xlim(0, 5) plt.ylim(0, 5) plt.grid(True) plt.title('Vector Addition (Head-to-Tail Method)') plt.show()
Parameters (based on the first quiver call):
ax.quiver(0, 0, 2, 1, color='blue', angles='xy', scale_units='xy', scale=1)
0, 0β starting point of the vector (origin);2, 1β vector components in the x and y directions;color='blue'β sets the arrow color to blue;angles='xy'β draws the arrow using Cartesian coordinates (xβy plane);scale_units='xy'β scales the arrow according to the same units as the axes;scale=1β keeps the arrowβs true length (no automatic scaling).
This plot shows the head-to-tail vector addition, where the red vector represents the sum v1β+v2β.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat