Skip to main content

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
note

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

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
tip

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
caution

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​

ordNameFormulaUse Case
2 (default)L2 / Euclidean√(Σ vᵢ²)Distance, standard magnitude
1L1 / ManhattanΣ |vᵢ|Sparse data, robust to outliers
0L0Count of non-zero elementsSparsity measure
np.infLāˆž / Maxmax(|vįµ¢|)Maximum component
-np.infL-āˆž / Minmin(|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.]
tip

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​

MethodCodeBest For
np.linalg.norm(v)One function callGeneral use (recommended)
np.sqrt(np.dot(v, v))Dot productPerformance on very large vectors
np.sqrt(np.sum(v**2))Explicit formulaEducational / clarity
math.sqrt(sum(x**2 ...))Pure PythonNo 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).