In linear algebra, the magnitude (or norm) of a vector represents its length. Computing vector magnitude is fundamental in many applications including physics simulations, machine learning (distance calculations, normalization), computer graphics, and signal processing. In this guide, we'll show you how to calculate vector magnitude using NumPy and explain the different types of norms.
Quick Answer: Use np.linalg.norm()
import numpy as np
vector = np.array([3, 4])
magnitude = np.linalg.norm(vector)
print(f"Magnitude: {magnitude}")Output:
Magnitude: 5.0What Is Vector Magnitude?
The magnitude of a vector V = (v₁, v₂, ..., vₙ) is computed as:
||V|| = √(v₁² + v₂² + ... + vₙ²)This is also called the Euclidean norm, L2 norm, or simply the length of the vector.
For example:
- Vector
[3, 4]→ √(9 + 16) = 5.0 - Vector
[1, 2, 3]→ √(1 + 4 + 9) = 3.742
Method 1: Using np.linalg.norm() (Recommended)
The numpy.linalg.norm() function is the standard way to compute vector magnitude in NumPy:
import numpy as np
v2d = np.array([3, 4])
print(f"2D magnitude: {np.linalg.norm(v2d)}")
v3d = np.array([1, 2, 3])
print(f"3D magnitude: {np.linalg.norm(v3d)}")
v5d = np.array([0, 1, 2, 3, 4])
print(f"5D magnitude: {np.linalg.norm(v5d)}")Output:
2D magnitude: 5.0
3D magnitude: 3.7416573867739413
5D magnitude: 5.477225575051661With Complex Numbers
import numpy as np
v = np.array([3 + 4j, 1 + 2j])
print(f"Complex magnitude: {np.linalg.norm(v):.4f}")Output:
Complex magnitude: 5.4772Method 2: Using the Mathematical Formula
You can compute the magnitude manually using NumPy operations:
import numpy as np
v = np.array([3, 4])
magnitude = np.sqrt(np.sum(v ** 2))
print(f"Manual (np): {magnitude}")
magnitude = np.sqrt(np.dot(v, v))
print(f"Dot product: {magnitude}")
magnitude = np.sqrt(v @ v)
print(f"@ operator: {magnitude}")Output:
Manual (np): 5.0
Dot product: 5.0
@ operator: 5.0Method 3: Using math.sqrt() (Pure Python)
For simple cases without NumPy dependency:
import math
def magnitude(vector):
return math.sqrt(sum(x ** 2 for x in vector))
v = [3, 4]
print(f"Magnitude: {magnitude(v)}")Output:
Magnitude: 5.0Understanding Different Norms
np.linalg.norm() supports different types of norms through the ord parameter:
Common Norms Explained
ord |
Name | Formula | Use Case |
|---|---|---|---|
2 (default) |
L2 / Euclidean | √(Σ vᵢ²) | Distance, standard magnitude |
1 |
L1 / Manhattan | Σ |vᵢ| | Sparse data, robust to outliers |
0 |
L0 | Count of non-zero elements | Sparsity measure |
np.inf |
L∞ / Max | max(|vᵢ|) | Maximum component |
-np.inf |
L-∞ / Min | min(|vᵢ|) | Minimum component |
Examples of Each Norm
import numpy as np
v = np.array([1, -2, 3, -4, 0])
print(f"Vector: {v}")
print(f"L0 norm (non-zero count): {np.linalg.norm(v, ord=0)}")
print(f"L1 norm (Manhattan): {np.linalg.norm(v, ord=1)}")
print(f"L2 norm (Euclidean): {np.linalg.norm(v, ord=2):.4f}")
print(f"L3 norm: {np.linalg.norm(v, ord=3):.4f}")
print(f"L∞ norm (max absolute): {np.linalg.norm(v, ord=np.inf)}")
print(f"L-∞ norm (min absolute): {np.linalg.norm(v, ord=-np.inf)}")Output:
Vector: [ 1 -2 3 -4 0]
L0 norm (non-zero count): 4.0
L1 norm (Manhattan): 10.0
L2 norm (Euclidean): 5.4772
L3 norm: 4.6416
L∞ norm (max absolute): 4.0
L-∞ norm (min absolute): 0.0Practical Use Cases
Normalizing a Vector (Unit Vector)
A unit vector has magnitude 1. Divide the vector by its magnitude to normalize it:
import numpy as np
v = np.array([3, 4])
magnitude = np.linalg.norm(v)
unit_vector = v / magnitude
print(f"Original: {v} (magnitude: {magnitude})")
print(f"Unit vector: {unit_vector} (magnitude: {np.linalg.norm(unit_vector):.1f})")Output:
Original: [3 4] (magnitude: 5.0)
Unit vector: [0.6 0.8] (magnitude: 1.0)Computing Distance Between Two Points
import numpy as np
point_a = np.array([1, 2, 3])
point_b = np.array([4, 6, 8])
distance = np.linalg.norm(point_b - point_a)
print(f"Distance: {distance:.4f}")Output:
Distance: 7.0711Computing Magnitudes for Multiple Vectors
import numpy as np
vectors = np.array([
[3, 4],
[1, 0],
[5, 12],
[8, 6]
])
magnitudes = np.linalg.norm(vectors, axis=1)
print(f"Vectors:\n{vectors}")
print(f"Magnitudes: {magnitudes}")Output:
Vectors:
[[ 3 4]
[ 1 0]
[ 5 12]
[ 8 6]]
Magnitudes: [ 5. 1. 13. 10.]Batch Normalization
import numpy as np
vectors = np.array([
[3, 4],
[1, 0],
[5, 12]
])
magnitudes = np.linalg.norm(vectors, axis=1, keepdims=True)
normalized = vectors / magnitudes
print("Normalized vectors:")
print(normalized)
print(f"Their magnitudes: {np.linalg.norm(normalized, axis=1)}")Output:
Normalized vectors:
[[0.6 0.8 ]
[1. 0. ]
[0.38461538 0.92307692]]
Their magnitudes: [1. 1. 1.]Method Comparison
| Method | Code | Best For |
|---|---|---|
np.linalg.norm(v) |
One function call | General use (recommended) |
np.sqrt(np.dot(v, v)) |
Dot product | Performance on very large vectors |
np.sqrt(np.sum(v**2)) |
Explicit formula | Educational / clarity |
math.sqrt(sum(x**2 ...)) |
Pure Python | No NumPy dependency |
Conclusion
To get the magnitude of a vector in NumPy, use np.linalg.norm(vector): it computes the Euclidean (L2) norm by default and supports other norms through the ord parameter.
For batch operations on multiple vectors, pass a 2D array with axis=1 to compute magnitudes row-wise.
The magnitude is essential for operations like normalization (dividing by the norm to get a unit vector) and distance computation (the norm of the difference between two points).