np.linalg.norm() for vector norms in NumPy - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time to calculate a vector's length grows as the vector gets bigger.
How does the work needed change when the vector size increases?
Analyze the time complexity of the following code snippet.
import numpy as np
vector = np.array([1, 2, 3, 4, 5])
norm_value = np.linalg.norm(vector)
This code calculates the length (norm) of a vector using numpy's built-in function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Summing the squares of each element in the vector.
- How many times: Once for each element in the vector (n times).
As the vector gets longer, the work grows in a straight line with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 multiplications and additions |
| 100 | About 100 multiplications and additions |
| 1000 | About 1000 multiplications and additions |
Pattern observation: Doubling the vector size roughly doubles the work needed.
Time Complexity: O(n)
This means the time to find the vector length grows directly with the number of elements.
[X] Wrong: "Calculating the norm takes the same time no matter how big the vector is."
[OK] Correct: The function must look at every element to compute the sum of squares, so bigger vectors take more time.
Knowing how vector length calculation scales helps you understand performance in many data tasks, like measuring distances or normalizing data.
"What if we calculate the norm of a matrix row-wise instead of a single vector? How would the time complexity change?"
Practice
np.linalg.norm() calculate by default when given a vector?Solution
Step 1: Understand the default behavior of np.linalg.norm()
By default,np.linalg.norm()calculates the Euclidean norm, which is the straight-line distance from the origin to the point represented by the vector.Step 2: Compare with other options
The sum, max, and product are different operations and not whatnp.linalg.norm()returns by default.Final Answer:
The Euclidean length (distance) of the vector -> Option CQuick Check:
Default norm = Euclidean length [OK]
- Confusing norm with sum of elements
- Thinking norm returns max element
- Assuming norm multiplies elements
v using np.linalg.norm()?Solution
Step 1: Recall the parameter name for norm order
The parameter to specify the norm order innp.linalg.norm()isord, notorder,norm, orp.Step 2: Check the correct syntax
Usingord=1correctly computes the 1-norm, which sums the absolute values of vector elements.Final Answer:
np.linalg.norm(v, ord=1) -> Option BQuick Check:
Use ord=1 for 1-norm [OK]
- Using 'order' instead of 'ord'
- Using 'norm' or 'p' as parameter names
- Omitting the ord parameter for 1-norm
import numpy as np v = np.array([3, 4]) norm_val = np.linalg.norm(v) print(norm_val)
Solution
Step 1: Calculate the Euclidean norm of vector [3, 4]
The Euclidean norm is sqrt(3^2 + 4^2) = sqrt(9 + 16) = sqrt(25) = 5.0.Step 2: Confirm the printed output
The code prints the norm value, which is 5.0.Final Answer:
5.0 -> Option AQuick Check:
Euclidean norm of [3,4] = 5.0 [OK]
- Adding elements instead of squaring and summing
- Forgetting to take square root
- Confusing norm with sum or max
import numpy as np v = np.array([1, -2, 3]) norm_val = np.linalg.norm(v, order=2) print(norm_val)
Solution
Step 1: Identify the parameter name error
The parameter to specify norm order isord, notorder. Usingordercauses a TypeError.Step 2: Confirm other options are incorrect
Negative values are allowed, np.linalg.norm accepts second argumentord, and numpy arrays are valid inputs.Final Answer:
The parameter name should be 'ord' not 'order' -> Option AQuick Check:
Use ord=2, not order=2 [OK]
- Using 'order' instead of 'ord'
- Thinking negative values cause error
- Believing np.linalg.norm takes only one argument
points. You want to normalize each point to have length 1 (unit vector). Which code correctly does this using np.linalg.norm()?Solution
Step 1: Calculate norms along rows with correct shape
Usingnp.linalg.norm(points, axis=1, keepdims=True)computes the Euclidean norm for each row and keeps the result as a column vector, allowing correct broadcasting for division.Step 2: Normalize each point by dividing by its norm
Dividingpointsby the norms with matching shape normalizes each row vector to length 1.Final Answer:
normalized = points / np.linalg.norm(points, axis=1, keepdims=True) -> Option DQuick Check:
Use keepdims=True for correct broadcasting [OK]
- Using axis=0 instead of axis=1 for row-wise normalization
- Using norm of whole array instead of per row
- Using ord=1 instead of default Euclidean norm
