How to Calculate a Vector's Magnitude (The Easy Way)
How to Calculate a Vector's Magnitude (The Easy Way)
Alright, so in our last video and post, we established that a simple list of numbers, like [3, 4]
, is actually a vector with a magnitude (length) and a direction. It’s the fundamental building block of machine learning.
So, how do we actually figure out its length? The good news is, we already know how to do it. Watch the video below for a quick visual explanation, then read on for the code and details.
The Intuition: It’s Just a Triangle
Let's go back to our vector v = [3, 4]
. Visually, it’s an arrow pointing from the origin to the point (3, 4). If we draw a line down from that point to the x-axis, we create a simple right-angled triangle.
We can find the length of the hypotenuse using the Pythagorean Theorem, which you probably remember from school
a² + b² = c²
So, the magnitude of our vector is simply the square root of 3² + 4²
, which is the square root of 9 + 16
, which is the square root of 25. The final length is 5.
That's it. The powerful formula for a vector's magnitude is just something we already know.
How to Code It
We can calculate this from scratch in Python, and it's a good way to understand what's happening under the hood.
From Scratch with the `math` library:
import math
v = [3, 4]
# Calculate the sum of squares
sum_of_squares = v[0]**2 + v[1]**2
# The magnitude is the square root
magnitude = math.sqrt(sum_of_squares)
print(magnitude)
# Output: 5.0
The Pro Way with NumPy:
In machine learning, we'll almost always use a library called NumPy. It has a built-in function called linalg.norm
that does all the work for you.
import numpy as np
v = np.array([3, 4])
# The linalg.norm function does the Pythagorean theorem for you!
magnitude = np.linalg.norm(v)
print(magnitude)
# Output: 5.0
The norm
function is just a fast and efficient way to do the same calculation. In ML, this specific type of magnitude is often called the "L2 Norm" of a vector. For now, just know that L2 Norm and magnitude are the same thing.
Conclusion
And that's it. You not only know what a vector is, but now you know how to calculate its most important property using both basic Python and the powerful NumPy library. This simple calculation is a core operation you'll see everywhere in machine learning.
Your Turn...
How would this calculation change for a 3D vector, like [3, 4, 5]
? Can you write a small Python function to calculate the magnitude for a vector of any size? Share your thoughts or code snippets in the comments!
This post is part of the "Decoding the Math of ML" series. For the first part of this series, check out the post: What is a Vector? (From a Developer's Perspective).
Comments
Post a Comment