Python NumPy: How to Get the Magnitude of a Vector
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.0
This computes the Euclidean norm (L2 norm): ā(3² + 4²) = ā(9 + 16) = ā25 = 5.0
What 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
# 2D vector
v2d = np.array([3, 4])
print(f"2D magnitude: {np.linalg.norm(v2d)}")
# 3D vector
v3d = np.array([1, 2, 3])
print(f"3D magnitude: {np.linalg.norm(v3d)}")
# Higher dimensions
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.477225575051661
With 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.4772
Method 2: Using the Mathematical Formulaā
You can compute the magnitude manually using NumPy operations:
import numpy as np
v = np.array([3, 4])
# Method 2a: Using np.sqrt and np.sum
magnitude = np.sqrt(np.sum(v ** 2))
print(f"Manual (np): {magnitude}")
# Method 2b: Using dot product
magnitude = np.sqrt(np.dot(v, v))
print(f"Dot product: {magnitude}")
# Method 2c: Using @ operator (matrix multiplication)
magnitude = np.sqrt(v @ v)
print(f"@ operator: {magnitude}")
Output:
Manual (np): 5.0
Dot product: 5.0
@ operator: 5.0
The dot product approach (np.sqrt(np.dot(v, v))) is mathematically equivalent to the L2 norm and can be slightly faster for very large vectors since it avoids creating an intermediate squared array.
Method 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.0
The pure Python approach is significantly slower for large vectors. Use np.linalg.norm() for performance-critical code.
Understanding 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.0
Practical 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.0711
Computing Magnitudes for Multiple Vectorsā
import numpy as np
# Each row is a vector
vectors = np.array([
[3, 4],
[1, 0],
[5, 12],
[8, 6]
])
# Compute magnitude for each row
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.]
The axis=1 parameter computes the norm across columns for each row (i.e., the magnitude of each row vector). Use axis=0 to compute across rows for each column.
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).