Module contents
Lesson 2 of 25Review 75 min

Vector spaces, linear independence, bases and dimension

A rigorous review of abstract structure: vector spaces beyond Rⁿ (polynomials, matrices and functions), subspaces, independence, bases and dimension. Prove the Steinitz exchange lemma, which makes dimension well defined, and discuss why numerical independence is a matter of degree rather than yes or no.

After this lesson you can

  • Verify the vector-space axioms and subspace criterion in nongeometric examples.
  • Decide whether vectors are linearly independent and extract a basis of their span.
  • Prove the Steinitz exchange lemma and deduce that all bases have the same cardinality.
  • Calculate a vector's coordinates in a given basis and compare bases of the same space.
  • Explain why in floating point the right question is how close vectors are to dependence.

Before you start

Why abstract?

In the previous lesson a vector was a list of numbers. That picture suffices for calculation but falls short when you look at what models manipulate. A degree-3 polynomial is not a list, yet it is added and scaled just like one. A grayscale image of 28×2828 \times 28 pixels is a function from the pixel grid to R\R, and the average of two images is another image. The update ΔW\Delta\mat{W} applied by fine-tuning to a transformer layer is a matrix, and combining two fine-tunings means adding matrices.

What these objects share is not their appearance, but their operations: they can be added and multiplied by numbers, and those operations obey familiar rules. This lesson’s abstraction forgets what the objects are and retains only how they combine. In return it provides three things.

  1. Economy. Each theorem is proved once and applies to lists, polynomials, matrices, functions and any example that appears tomorrow.
  2. Dimension. A number measures how many independent pieces of information are needed to describe an object. Polynomials of degree ≤3\le 3 form a space of dimension 4: any cubic is fixed by 4 numbers. But which 4 numbers is a choice (a basis), and choosing well drastically changes numerical stability.
  3. Precision. The question “do these vectors add new information?” becomes exact. You will see that in floating point it ceases to have a simple yes-or-no answer.

Dimension is not a textbook curiosity. Li et al. (2018) train networks by restricting parameters to a random affine subspace θ=θ0+Pz\theta = \theta_0 + \mat{P}\vb{z}, with z∈Rd\vb{z} \in \R^d and dd much smaller than the total number of parameters, and call the smallest dd yielding good solutions the problem’s intrinsic dimension (in practice, the one reaching 90% of unrestricted training performance). Aghajanyan et al. (2020) take the idea to language-model fine-tuning: optimizing only 200 parameters randomly projected into the full space, RoBERTa reaches 90% of full fine-tuning performance on MRPC. LoRA (Hu et al., 2021) starts from a related hypothesis: each weight-matrix update has low rank. Reading these papers precisely requires this lesson’s notions: subspace, affine subspace, independence and dimension.

First look: how many directions fit?

Recall that the span of v1,…,vk\vb{v}_1, \dots, \vb{v}_k is the set of all their linear combinations c1v1+⋯+ckvkc_1\vb{v}_1 + \dots + c_k\vb{v}_k. In R3\R^3, the span of one nonzero vector is a line through the origin; of two vectors, a plane unless they are parallel; of three, the whole space unless they lie in one plane. We will formalize the number of genuinely new directions as dimension.

InteractiveSpan builder in R3\R^3
  • span
  • generated parallelogram
Relative singular values σi/σ1\sigma_i/\sigma_1 (log scale): numerical rank counts bars above τ\tau.
numerical zero10−1610−1210−810−4100σ₁1.00σ₂0.94τ = 1e−10
Number of vectors kk
Selected vector
0.40
2.00
0.60
1e−10
dim⁡span⁡\dim \spn (numerical rank)2
a plane
Area of the parallelogram4.412
Normalized volume ν\nu0.999
Independent: each vector adds a new direction.
Start with two vectors, which span a plane. Change kk and drag the tips (or use the sliders): the blue span changes from a line to a plane and all of R3\R^3. Select Nearly coplanar: the yellow parallelepiped flattens into a sheet and the computer's reported dimension depends on tolerance τ\tau. With Coplanar, lower τ\tau to the extreme: the computer sees a third direction that does not exist.

Three observations from the experiment are useful before formalizing anything.

A vector already in the span of the others adds nothing. With Coplanar, v3=v1+v2\vb{v}_3 = \vb{v}_1 + \vb{v}_2 and the span of all three is the same plane as that of the first two. Three vectors do not guarantee three directions.

Volume detects dependence. The volume of the parallelepiped generated by three vectors in R3\R^3 is ∣det⁡[v1 v2 v3]∣\abs{\det[\vb{v}_1\ \vb{v}_2\ \vb{v}_3]} (you will justify this in the determinants lesson), and vanishes exactly when one lies in the plane of the other two. Since volume grows with vector length, the useful quantity is normalized volume

ν=∣det⁡[v1 v2 v3]∣∥v1∥∥v2∥∥v3∥∈[0,1],\nu = \frac{\abs{\det[\vb{v}_1\ \vb{v}_2\ \vb{v}_3]}}{\norm{\vb{v}_1}\norm{\vb{v}_2}\norm{\vb{v}_3}} \in [0, 1],

which is 1 if the vectors are pairwise perpendicular and 0 if they are dependent (ν≤1\nu \le 1 is Hadamard’s inequality).

The boundary is blurred. With Nearly coplanar, v3\vb{v}_3 lies at distance h≈0.04h \approx 0.04 from the plane of v1,v2\vb{v}_1, \vb{v}_2 and ν≈0.02\nu \approx 0.02. In exact arithmetic the three vectors are independent, but if their coordinates come from measurements with error 0.050.05, the third direction is noise. The lower strip shows relative singular values σi/σ1\sigma_i/\sigma_1, studied in depth with the SVD: the computer counts directions exceeding a tolerance τ\tau, and raising τ\tau above σ3/σ1≈0.01\sigma_3/\sigma_1 \approx 0.01 changes the answer. Even exact dependence is not immune: with Coplanar, σ3/σ1\sigma_3/\sigma_1 is not 0 but about 5⋅10−185 \cdot 10^{-18}, and with τ\tau at its minimum the computer sees a third direction. The floating-point section explains why.

Vector spaces

Notice what the definition does not say: nothing about what vectors are, nor lengths, angles or products between vectors (those arrive with inner products). Also notice what “operation” hides: the sum of two elements of VV and scalar multiplication must lie in VV. This closure is the condition that most often fails in examples.

Examples you will use daily:

SpaceVectorsOperationsZero
Rn\R^nlists (x1,…,xn)(x_1, \dots, x_n)componentwise(0,…,0)(0, \dots, 0)
Rm×n\R^{m \times n}matricesentrywisezero matrix
Pn\mathcal{P}_npolynomials of degree ≤n\le ncoefficientwisezero polynomial
C[a,b]C[a, b]continuous functions on [a,b][a, b]pointwisefunction f≡0f \equiv 0
RX\R^Xfunctions X→RX \to \R, with XX any setpointwisezero function

The last includes the others. A list of Rn\R^n is a function {1,…,n}→R\{1, \dots, n\} \to \R; a matrix of Rm×n\R^{m \times n}, a function {1,…,m}×{1,…,n}→R\{1, \dots, m\} \times \{1, \dots, n\} \to \R; a sequence, a function N→R\N \to \R; an image of 28×2828 \times 28, a vector of R784\R^{784}. In RX\R^X addition and multiplication are defined pointwise, (f+g)(x)=f(x)+g(x)(f + g)(x) = f(x) + g(x) and (λf)(x)=λf(x)(\lambda f)(x) = \lambda f(x), and all eight axioms are inherited from those of R\R at each point. Thus an activation tensor of shape B×T×dB \times T \times d is simply a vector in RB×T×d\R^{B \times T \times d}, which is RBTd\R^{BTd} with different indexing.

The axioms imply rules you use without thinking. They are worth seeing once because in the previous example they assert things that are far from obvious, such as 0⊡x0 \boxdot x being the identity 11.

Proof

If 0\vb{0} and 0′\vb{0}' are identities, 0=0+0′=0′\vb{0} = \vb{0} + \vb{0}' = \vb{0}'. If w\vb{w} and w′\vb{w}' are inverses of v\vb{v}, then w=w+(v+w′)=(w+v)+w′=w′\vb{w} = \vb{w} + (\vb{v} + \vb{w}') = (\vb{w} + \vb{v}) + \vb{w}' = \vb{w}'. For 0v0\vb{v}:

0v=(0+0)v=0v+0v0\vb{v} = (0 + 0)\vb{v} = 0\vb{v} + 0\vb{v}
Axiom 8 with a = b = 0.
1/3

The same trick with a0=a(0+0)=a0+a0a\vb{0} = a(\vb{0} + \vb{0}) = a\vb{0} + a\vb{0} gives a0=0a\vb{0} = \vb{0}. Finally, v+(−1)v=1v+(−1)v=(1−1)v=0v=0\vb{v} + (-1)\vb{v} = 1\vb{v} + (-1)\vb{v} = (1 - 1)\vb{v} = 0\vb{v} = \vb{0}, so (−1)v(-1)\vb{v} is an inverse of v\vb{v} and, by uniqueness, is −v-\vb{v}.

∎

Subspaces

Almost all vector spaces encountered in practice live inside a larger one: solutions of a homogeneous system inside Rn\R^n, symmetric matrices inside Rn×n\R^{n \times n}, polynomials inside continuous functions. For these there is no need to check all eight axioms.

Proof

If UU is a subspace, (ii) and (iii) express closure of its operations. For (i), the identity 0U\vb{0}_U of UU satisfies 0U+0U=0U\vb{0}_U + \vb{0}_U = \vb{0}_U in VV; adding −0U-\vb{0}_U gives 0U=0\vb{0}_U = \vb{0}. Conversely, if (i), (ii) and (iii) hold, the operations are well-defined in UU; axioms 1, 2 and 5–8 are equalities holding in VV and therefore in UU; the identity is present by (i); and the inverse of u∈U\vb{u} \in U is −u=(−1)u∈U-\vb{u} = (-1)\vb{u} \in U by (iii) and the previous proposition. In the equivalent form, U≠∅U \neq \emptyset suffices instead of (i): if u∈U\vb{u} \in U, then 0=0u∈U\vb{0} = 0\vb{u} \in U.

∎

Examples of subspaces, all by the same one-line argument:

  • {0}\{\vb{0}\} and VV (the trivial ones); lines and planes in R3\R^3 through the origin.
  • The solution set of a homogeneous system Ax=0\mat{A}\vb{x} = \vb{0}, because A(ax+by)=aAx+bAy=0\mat{A}(a\vb{x} + b\vb{y}) = a\mat{A}\vb{x} + b\mat{A}\vb{y} = \vb{0}. This is the null space (or kernel) of A\mat{A}. Note: in kernel methods, kernel means something else, a similarity function.
  • The span of any set SS: it is a subspace and the smallest containing SS, because every subspace containing SS contains all its combinations.
  • P2⊂P3⊂C[a,b]\mathcal{P}_2 \subset \mathcal{P}_3 \subset C[a, b]; symmetric, upper-triangular and zero-trace matrices within Rn×n\R^{n \times n}.
  • {f∈C[0,1]:f(0)=0}\{f \in C[0, 1] : f(0) = 0\} and, within C2(R)C^2(\R), the solution set of differential equation f′′+f=0f'' + f = 0.

And counterexamples worth keeping in mind:

  • A hyperplane not passing through the origin, {x:a⊤x=1}\{\vb{x} : \vb{a}\T\vb{x} = 1\} with a≠0\vb{a} \neq \vb{0} (a line in R2\R^2): it does not contain 0\vb{0}. It is an affine subspace, a translated subspace p+U\vb{p} + U, like θ0+Pz\theta_0 + \mat{P}\vb{z} in the motivation.
  • The union of two lines through the origin: closed under scalar multiplication, but not addition.
  • A half-plane {y≥0}\{y \ge 0\}: closed under addition and nonnegative scalars (a convex cone), but not λ<0\lambda < 0.
  • The probability simplex {p≥0:∑ipi=1}\{\vb{p} \ge \vb{0} : \sum_i p_i = 1\}: it neither contains 0\vb{0} nor is closed under addition.
  • Matrices m×nm \times n of rank ≤r\le r, with 1≤r<min⁡(m,n)1 \le r < \min(m, n): closed under scalars, but (E11+⋯+Err)+Er+1,r+1(\mat{E}_{11} + \dots + \mat{E}_{rr}) + \mat{E}_{r+1,r+1} has rank r+1r + 1 although each summand has rank ≤r\le r. Thus the set of LoRA updates ΔW=BA\Delta\mat{W} = \mat{B}\mat{A}, with B\mat{B} of rr columns, is not a subspace: it is a cone (closed under scalars) that is not closed under addition, an algebraic variety studied with low-rank approximation. The sum of two rank-rr LoRA updates guarantees only rank ≤2r\le 2r, which matters when merging them.
InteractiveIs it a subspace?
  • set SS
  • u\vb{u}
  • w\vb{w}
  • result in SS
  • result outside SS
S={(x,y):y≥0}S = \{(x, y) : y \ge 0\}
1.8
0∈S\vb{0} \in Syes
u+w∈S\vb{u} + \vb{w} \in Syes
λu∈S\lambda\vb{u} \in Syes
Find u,w∈S\vb{u}, \vb{w} \in S and a λ\lambda that move the result outside SS, or convince yourself none exist.
Choose a set SS in the plane and drag u,w∈S\vb{u}, \vb{w} \in S. Change λ\lambda. The sum and multiple are marked red when they leave SS: try to break each set before requesting the counterexample. Only one survives.

Intersection, union and sum

The intersection of subspaces is a subspace. Their union almost never is: U∪WU \cup W is a subspace only when one contains the other. You will prove both in the exercises. The correct substitute for union is the sum

U+W={u+w:u∈U, w∈W}=span⁡(U∪W),U + W = \{\vb{u} + \vb{w} : \vb{u} \in U, \ \vb{w} \in W\} = \spn(U \cup W),

the smallest subspace containing both. When U∩W={0}U \cap W = \{\vb{0}\} the sum is direct, U⊕WU \oplus W, and each vector in U+WU + W decomposes uniquely: if u+w=u′+w′\vb{u} + \vb{w} = \vb{u}' + \vb{w}', then u−u′=w′−w∈U∩W={0}\vb{u} - \vb{u}' = \vb{w}' - \vb{w} \in U \cap W = \{\vb{0}\}.

For more than two summands, the correct condition is that each UiU_i intersects the sum of the others only in 0\vb{0} (after Grassmann’s formula you will see this is equivalent to dim⁡∑iUi=∑idim⁡Ui\dim \sum_i U_i = \sum_i \dim U_i). Trivial pairwise intersections are insufficient: three distinct lines in R2\R^2 through the origin intersect pairwise only in 0\vb{0}, and their sum, R2\R^2, is not direct because each vector has infinitely many decompositions.

Linear independence

This is the definition of linear independence. We deliberately speak of lists rather than sets: a list with a repeated vector is dependent (v−v=0\vb{v} - \vb{v} = \vb{0}), and order will matter when we discuss coordinates. The three readings of the definition are equivalent and useful to know.

Proof

(1 ⇔ 2) If vj=∑i≠jcivi\vb{v}_j = \sum_{i \neq j} c_i\vb{v}_i, then ∑i≠jcivi−vj=0\sum_{i \neq j} c_i\vb{v}_i - \vb{v}_j = \vb{0} is a nontrivial relation (the coefficient of vj\vb{v}_j is −1-1). Conversely, if ∑iaivi=0\sum_i a_i\vb{v}_i = \vb{0} with some aj≠0a_j \neq 0, rearranging gives vj=−∑i≠j(ai/aj)vi\vb{v}_j = -\sum_{i \neq j} (a_i/a_j)\vb{v}_i.

(1 ⇒ 3) If ∑iaivi=∑ibivi\sum_i a_i\vb{v}_i = \sum_i b_i\vb{v}_i, subtraction gives ∑i(ai−bi)vi=0\sum_i (a_i - b_i)\vb{v}_i = \vb{0}, and independence gives ai=bia_i = b_i. (3 ⇒ 1) 0=∑i0 vi\vb{0} = \sum_i 0\,\vb{v}_i is a representation of 0\vb{0}; by uniqueness, any combination equal to 0\vb{0} is trivial.

∎

The piece that makes everything that follows work is an ordered version of the second face, the linear dependence lemma.

Proof

Take a nontrivial relation ∑iaivi=0\sum_i a_i\vb{v}_i = \vb{0} and let jj be the largest index with aj≠0a_j \neq 0. Then vj=−∑i<j(ai/aj)vi\vb{v}_j = -\sum_{i < j} (a_i/a_j)\vb{v}_i (if j=1j = 1, this says v1=0\vb{v}_1 = \vb{0}, which lies in span⁡(∅)={0}\spn(\emptyset) = \{\vb{0}\}). Any combination of the full list becomes one without vj\vb{v}_j by replacing vj\vb{v}_j with that expression, so the span is unchanged.

∎

The test in Rn\R^n. If vectors are columns of V=[v1 ⋯ vk]∈Rn×k\mat{V} = [\vb{v}_1\ \cdots\ \vb{v}_k] \in \R^{n \times k}, a combination ∑iaivi\sum_i a_i\vb{v}_i is the product Va\mat{V}\vb{a}. The list is independent if and only if the homogeneous system Va=0\mat{V}\vb{a} = \vb{0} has only the trivial solution, that is, if Gaussian elimination leaves a pivot in every column. If k>nk > n there are more unknowns than equations, a variable is free and the list is dependent: Rn\R^n holds at most nn independent vectors. This is a special case of the next section’s exchange lemma.

Outside Rn\R^n the test is the same, but the equation lives in a function space:

  • (1,x,x2,…,xn)(1, x, x^2, \dots, x^n) is independent: if ∑kakxk=0\sum_k a_k x^k = 0 for every xx, the polynomial has infinitely many roots and all coefficients are zero (or, differentiating kk times at 00, k! ak=0k!\,a_k = 0).
  • (sin⁡,cos⁡)(\sin, \cos) is independent in C(R)C(\R): from asin⁡x+bcos⁡x=0a\sin x + b\cos x = 0 for every xx, evaluating at x=0x = 0 gives b=0b = 0, and at x=π/2x = \pi/2 gives a=0a = 0.
  • (1,cos⁡2,sin⁡2)(1, \cos^2, \sin^2) is dependent: 1−cos⁡2x−sin⁡2x=01 - \cos^2 x - \sin^2 x = 0. Very different-looking functions can be dependent.

The exchange lemma and dimension

Intuitively, R3\R^3 has “three directions” and a plane “two.” Making that intuition a well-defined number requires proving something nonobvious: there cannot be more independent vectors than vectors in a spanning list, a list whose span is the whole space. This is the Steinitz exchange lemma, the lesson’s central result.

The idea is to put u\vb{u} into the spanning list one at a time and, each time, remove one w\vb{w} in exchange while keeping the list spanning VV. If we ran out of w\vb{w} to remove, the incoming u\vb{u} would be a combination of the preceding u\vb{u}, contradicting independence.

InteractiveThe exchange lemma, step by step
Case
WW has 4 vectors spanning R3\R^3 (one is redundant: the list is dependent); UU has 3 independent vectors.
To insert (independent list UU)
u1\vb{u}_{1}(1, 1, 1)
u2\vb{u}_{2}(0, 2, −1)
u3\vb{u}_{3}(2, 0, 1)
Spanning list LL
w1\vb{w}_{1}(1, 0, 0)
w2\vb{w}_{2}(1, 1, 0)
w3\vb{w}_{3}(0, 1, 1)
w4\vb{w}_{4}(1, 2, 1)
When choosing what leaves:thick border: b≠0b \neq 0, can be removeddashed: b=0b = 0 here, but not in every representationdimmed: b=0b = 0 in all, cannot be removed
The list L=(w1,…,w4)L = (\vb{w}_1, \dots, \vb{w}_4) spans R3\R^3. Insert u1\vb{u}_1.
Exchanges: none yet.
Length of LL4
dim⁡span⁡L\dim \spn L (3: spans R3\R^3)3
u\vb{u} inserted0 of 3
w\vb{w} remaining4
Introduce the u\vb{u} one at a time. Each incoming u\vb{u} is written as a combination of the current list; select a w\vb{w} with coefficient b≠0b \neq 0 to remove it, and watch the invariant dim⁡span⁡L=3\dim\spn L = 3. For k=3k = 3 the list is dependent: select a w\vb{w} with b=0b = 0 to see another equally valid representation where b≠0b \neq 0. For k=4k = 4, WW is a basis and representation is unique: try to remove w2\vb{w}_2 in the first step (b=0b = 0) and the list would no longer span R3\R^3. Continue to the end and the algorithm encounters the contradiction.

The proof is collapsed: before opening it, try the guided version.

ProofExchange lemma
Prove: If VV is spanned by (w1,…,wm)(\vb{w}_1, \dots, \vb{w}_m) and (u1,…,uk)(\vb{u}_1, \dots, \vb{u}_k) is independent in VV, then k≤mk \le m. Consequently, all bases of a finite-dimensional space have the same length.
0
We prove by induction on t=0,…,kt = 0, \dots, k the claim P(t)P(t): t≤mt \le m and, after reordering the wj\vb{w}_j, the list Lt=(u1,…,ut,wt+1,…,wm)L_t = (\vb{u}_1, \dots, \vb{u}_t, \vb{w}_{t+1}, \dots, \vb{w}_m) spans VV.

Step 1 of 5. Why does the base case P(0)P(0) hold?

Proof

We prove by induction on t=0,1,…,kt = 0, 1, \dots, k the claim

P(t)P(t): t≤mt \le m and, after reordering wj\vb{w}_j, list Lt=(u1,…,ut,wt+1,…,wm)L_t = (\vb{u}_1, \dots, \vb{u}_t, \vb{w}_{t+1}, \dots, \vb{w}_m) spans VV.

P(0)P(0) is the hypothesis. Suppose P(t)P(t) with t<kt < k. Since ut+1∈V=span⁡Lt\vb{u}_{t+1} \in V = \spn L_t,

ut+1=∑i=1taiui+∑j=t+1mbjwj.\vb{u}_{t+1} = \sum_{i=1}^{t} a_i\vb{u}_i + \sum_{j=t+1}^{m} b_j\vb{w}_j.

If all bjb_j were zero (in particular, if t=mt = m and no w\vb{w} remained), we would have ut+1−∑i≤taiui=0\vb{u}_{t+1} - \sum_{i \le t} a_i\vb{u}_i = \vb{0}, a nontrivial relation among u\vb{u} (the coefficient of ut+1\vb{u}_{t+1} is 1), contradicting independence (a proof by contradiction). Thus some bj≠0b_j \neq 0, which in particular requires t+1≤mt + 1 \le m. Reorder, suppose bt+1≠0b_{t+1} \neq 0 and rearrange:

wt+1=1bt+1(ut+1−∑i=1taiui−∑j=t+2mbjwj).\vb{w}_{t+1} = \frac{1}{b_{t+1}}\Big(\vb{u}_{t+1} - \sum_{i=1}^{t} a_i\vb{u}_i - \sum_{j=t+2}^{m} b_j\vb{w}_j\Big).

Thus wt+1\vb{w}_{t+1} is a combination of Lt+1=(u1,…,ut+1,wt+2,…,wm)L_{t+1} = (\vb{u}_1, \dots, \vb{u}_{t+1}, \vb{w}_{t+2}, \dots, \vb{w}_m), and the remaining vectors of LtL_t are in Lt+1L_{t+1}. Therefore span⁡Lt+1⊇span⁡Lt=V\spn L_{t+1} \supseteq \spn L_t = V, which is P(t+1)P(t+1). With t=kt = k we obtain k≤mk \le m and the rest of the claim.

∎

Two proof details are visible in the interactive. The outgoing vector must have a nonzero coefficient in the chosen representation: only then can it be isolated. If LtL_t is dependent, that representation is not unique, and wj\vb{w}_j with zero coefficient in one can have a nonzero coefficient in another; the coefficient belongs to the representation, not the vector. The intermediate list LtL_t need not be independent; only its spanning of VV is preserved, and that invariant plus independence of u\vb{u} suffices. When there are several candidates, choosing the largest ∣bj∣\abs{b_j} is the same idea as partial pivoting in Gaussian elimination: divide by the largest available coefficient.

Bases and dimension

Proof

Let B\mathcal{B} and B′\mathcal{B}' be bases with nn and n′n' elements. B′\mathcal{B}' is independent and B\mathcal{B} spans, so n′≤nn' \le n by the exchange lemma. Reversing their roles gives n≤n′n \le n'.

∎

Without the exchange lemma this definition would make no sense: bases could have different lengths. The edge case fits too: the basis of {0}\{\vb{0}\} is the empty list (independent by convention, with span {0}\{\vb{0}\}), so dim⁡{0}=0\dim\{\vb{0}\} = 0.

Proof

(1) While the list is dependent, the dependence lemma allows removal of a vector without changing the span; the process terminates because the list is finite, leaving an independent list that still spans VV. (2) Let (u1,…,uk)(\vb{u}_1, \dots, \vb{u}_k) be independent and (w1,…,wm)(\vb{w}_1, \dots, \vb{w}_m) spanning. Go through wj\vb{w}_j and add each one outside the current span. Adding a vector outside the span of an independent list preserves independence (if w\vb{w} appeared in a relation with nonzero coefficient, it could be isolated and would be in the span). At the end, all wj\vb{w}_j are in the list’s span, which therefore spans VV.

∎
Proof

(1) is the exchange lemma applied against a basis. (2) An independent list of length nn extends to a basis with nn elements, so nothing is added: it was already a basis. A spanning list of length nn reduces to a basis of nn elements, so nothing is removed. (3) We do not yet know UU is finite-dimensional, so construct a basis by hand: start with the empty list and, while it does not span UU, add a vector of UU outside its span. The list remains independent (by the preceding proposition) and is an independent list in VV, so it never exceeds nn vectors: the process stops in at most nn steps, and stops only when the list spans UU. It is a basis of UU, so dim⁡U≤n\dim U \le n. If dim⁡U=n\dim U = n, a basis of UU is an independent list of nn vectors in VV, so by (2) it is a basis of VV and U=VU = V.

∎
Proof

By (3), UU has a basis (u1,…,uk)(\vb{u}_1, \dots, \vb{u}_k). Extend it to a basis (u1,…,uk,w1,…,wl)(\vb{u}_1, \dots, \vb{u}_k, \vb{w}_1, \dots, \vb{w}_l) of VV and take W=span⁡(w1,…,wl)W = \spn(\vb{w}_1, \dots, \vb{w}_l). Every vector in VV is a combination of that basis, hence lies in U+WU + W. If x∈U∩W\vb{x} \in U \cap W, then x=∑iaiui=∑jbjwj\vb{x} = \sum_i a_i\vb{u}_i = \sum_j b_j\vb{w}_j; subtracting, basis independence gives ai=bj=0a_i = b_j = 0, that is, x=0\vb{x} = \vb{0}.

∎

The complement is not unique: in R2\R^2, any line through the origin other than UU complements line UU. The same construction, extending a subspace basis to one of the entire space, proves the rank–nullity theorem.

Proof

Let (z1,…,zr)(\vb{z}_1, \dots, \vb{z}_r) be a basis of U∩WU \cap W. Extend it to a basis (z,u1,…,us)(\vb{z}, \vb{u}_1, \dots, \vb{u}_s) of UU and a basis (z,w1,…,wt)(\vb{z}, \vb{w}_1, \dots, \vb{w}_t) of WW. List (z,u,w)(\vb{z}, \vb{u}, \vb{w}) spans U+WU + W. It is independent: if ∑cizi+∑aiui+∑biwi=0\sum c_i\vb{z}_i + \sum a_i\vb{u}_i + \sum b_i\vb{w}_i = \vb{0}, vector ∑biwi=−∑cizi−∑aiui\sum b_i\vb{w}_i = -\sum c_i\vb{z}_i - \sum a_i\vb{u}_i lies in both WW and UU, hence in U∩WU \cap W, and can be written ∑biwi=∑dizi\sum b_i\vb{w}_i = \sum d_i\vb{z}_i. Since (z,w)(\vb{z}, \vb{w}) is independent, all bib_i (and did_i) are zero; ∑cizi+∑aiui=0\sum c_i\vb{z}_i + \sum a_i\vb{u}_i = \vb{0} remains, and independence of (z,u)(\vb{z}, \vb{u}) makes the rest zero. Thus dim⁡(U+W)=r+s+t=(r+s)+(r+t)−r\dim(U + W) = r + s + t = (r + s) + (r + t) - r.

∎

The formula has a useful high-dimensional consequence: two large subspaces cannot avoid each other. Two planes through the origin in R3\R^3 intersect in at least a line, because dim⁡(U∩W)≥2+2−3=1\dim(U \cap W) \ge 2 + 2 - 3 = 1. In a 768-dimensional embedding space, two 500-dimensional subspaces share at least 500+500−768=232500 + 500 - 768 = 232 dimensions.

For two summands the formula also characterizes direct sum: dim⁡(U+W)=dim⁡U+dim⁡W\dim(U + W) = \dim U + \dim W if and only if dim⁡(U∩W)=0\dim(U \cap W) = 0, that is, if and only if U∩W={0}U \cap W = \{\vb{0}\}. The version with more summands is the one announced in the subspaces section.

Proof

Concatenate a basis of each UiU_i. The resulting list B\mathcal{B} spans the sum and has ∑idim⁡Ui\sum_i \dim U_i vectors, so equality of dimensions is equivalent to independence of B\mathcal{B} (if dependent, it could be reduced to a shorter basis). If B\mathcal{B} is dependent, group a nontrivial relation by blocks: x1+⋯+xk=0\vb{x}_1 + \dots + \vb{x}_k = \vb{0} with xi∈Ui\vb{x}_i \in U_i, and some xi\vb{x}_i is nonzero because each block is independent; that xi=−∑j≠ixj\vb{x}_i = -\sum_{j \neq i}\vb{x}_j lies in UiU_i and in the sum of the others. Conversely, if an x≠0\vb{x} \neq \vb{0} of UiU_i is ∑j≠ixj\sum_{j \neq i}\vb{x}_j with xj∈Uj\vb{x}_j \in U_j, expanding each term in its basis gives a relation among the vectors of B\mathcal{B} with some nonzero coefficient in block ii.

∎

Some dimensions worth memorizing:

SpaceBasisDimension
Rn\R^nstandard e1,…,en\vb{e}_1, \dots, \vb{e}_nnn
Rm×n\R^{m \times n}matrices Eij\mat{E}_{ij} with a 1 at (i,j)(i, j)mnmn
Pn\mathcal{P}_n1,x,…,xn1, x, \dots, x^nn+1n + 1
symmetric matrices n×nn \times nEii\mat{E}_{ii} and Eij+Eji\mat{E}_{ij} + \mat{E}_{ji} with i<ji \lt jn(n+1)/2n(n+1)/2
antisymmetric matrices n×nn \times nEij−Eji\mat{E}_{ij} - \mat{E}_{ji} with i<ji \lt jn(n−1)/2n(n-1)/2
solutions of f′′+f=0f'' + f = 0cos⁡,sin⁡\cos, \sin22

Bases and coordinates

A basis is exactly what is needed to turn an abstract vector into a list of numbers.

The map v↦[v]B\vb{v} \mapsto [\vb{v}]_{\mathcal{B}} is bijective and respects operations: [u+w]B=[u]B+[w]B[\vb{u} + \vb{w}]_{\mathcal{B}} = [\vb{u}]_{\mathcal{B}} + [\vb{w}]_{\mathcal{B}} and [λv]B=λ[v]B[\lambda\vb{v}]_{\mathcal{B}} = \lambda[\vb{v}]_{\mathcal{B}} (add the representations and use uniqueness). It is an isomorphism, a bijective linear map: every real space of dimension nn is isomorphic to Rn\R^n, and two finite-dimensional spaces are isomorphic if and only if they have the same dimension (an isomorphism maps bases to bases). This explains why we can calculate with arrays regardless of the space. But the copy depends on the chosen basis, and none is privileged: P3\mathcal{P}_3 does not come with a “standard” basis built in. Choosing a basis is a design decision, and the next lesson (change of basis) explains translation between choices.

Calculating coordinates in Rn\R^n means solving a system. If B=[b1 ⋯ bn]\mat{B} = [\vb{b}_1\ \cdots\ \vb{b}_n], equation v=∑icibi\vb{v} = \sum_i c_i\vb{b}_i is Bc=v\mat{B}\vb{c} = \vb{v}, so [v]B=B−1v[\vb{v}]_{\mathcal{B}} = \mat{B}\inv\vb{v}. For example, with b1=(2,1)\vb{b}_1 = (2, 1) and b2=(1,1)\vb{b}_2 = (1, 1), coordinates of v=(1,2)\vb{v} = (1, 2) come from 2c1+c2=12c_1 + c_2 = 1 and c1+c2=2c_1 + c_2 = 2: [v]B=(−1,3)[\vb{v}]_{\mathcal{B}} = (-1, 3). The code solves the system; it never computes the inverse (the next lesson explains why when introducing the matrix inverse).

InteractiveCoordinates in a deformable basis
  • b1\vb{b}_1 and span⁡(b1)\spn(\vb{b}_1)
  • b2\vb{b}_2 and span⁡(b2)\spn(\vb{b}_2)
  • basis grid (c1c_1 or c2c_2 integer)
  • v\vb{v} and its coordinates
  • uncertainty
Plane: v=c1b1+c2b2\vb{v} = c_1\vb{b}_1 + c_2\vb{b}_2
Coordinates: [v]B=B−1v[\vb{v}]_{\mathcal{B}} = \mat{B}^{-1}\vb{v}
B−1\mat{B}^{-1} maps the basis grid to the standard grid and the disk of radius δ\delta to an ellipse with semiaxes δ/σ1=0.11\delta/\sigma_1 = 0.11 and δ/σ2=0.21\delta/\sigma_2 = 0.21.
0.25
[v]B=(c1,c2)[\vb{v}]_{\mathcal{B}} = (c_1, c_2)(0.45, 1.18)
det⁡B\det \mat{B}2.750
Angle between b1\vb{b}_1 and b2\vb{b}_257.5°
Amplification 1/σmin⁡(B)1/\sigma_{\min}(\mat{B})0.84
κ(B)=σmax⁡/σmin⁡\kappa(\mat{B}) = \sigma_{\max}/\sigma_{\min}1.9
The gray grid on the left is the basis grid: lines c1=c_1 = constant (parallel to b2\vb{b}_2) and c2=c_2 = constant (parallel to b1\vb{b}_1) at integer values. Read the coordinates of v\vb{v} and compare them with the right panel, where the same grid is standard. Then select Nearly parallel, or move b2\vb{b}_2 close to the direction of b1\vb{b}_1 and release: both panels zoom out to fit the decomposition, and the uncertainty disk of v\vb{v} becomes a huge ellipse.

The interactive teaches two things. The first is geometric: B−1\mat{B}\inv takes the distorted basis grid to the standard grid, and coordinates are simply the position of v\vb{v} on that grid. The second is numerical and most important to an engineer. When b1\vb{b}_1 and b2\vb{b}_2 are nearly parallel, the basis remains a basis in exact arithmetic, but a small error in v\vb{v} becomes a huge error in [v]B[\vb{v}]_{\mathcal{B}}: a disk of radius δ\delta becomes an ellipse whose major semiaxis is δ/σmin⁡(B)\delta/\sigma_{\min}(\mat{B}). The ratio κ(B)=σmax⁡/σmin⁡\kappa(\mat{B}) = \sigma_{\max}/\sigma_{\min} is the condition number, which throughout the module measures error amplification.

[ ]Coordinates: solve, do not invertBrowser
import numpy as np

B = np.column_stack([[2.0, 1.0], [1.0, 1.0]])     # columnas b1, b2
v = np.array([1.0, 2.0])
print("coordenadas de v:", np.linalg.solve(B, v))   # (-1, 3)

# una base casi degenerada: b2 casi paralelo a b1
Bc = np.column_stack([[2.0, 1.0], [2.0, 1.001]])
dv = np.array([0.0, 1e-3])                # perturbación diminuta de v
print("c      =", np.linalg.solve(Bc, v))
print("c + dc =", np.linalg.solve(Bc, v + dv))
print("1/sigma_min =", 1 / np.linalg.svd(Bc, compute_uv=False)[-1])

A perturbation of size 10−310^{-3} in v\vb{v} moves each coordinate by a whole unit, and the coordinate vector 2≈1.41\sqrt2 \approx 1.41: a factor of about 1400, close to the worst-case bound 1/σmin⁡≈15811/\sigma_{\min} \approx 1581.

Polynomials: three bases for the same space

An example where basis choice really matters is P3\mathcal{P}_3, polynomials of degree ≤3\le 3 on [0,1][0, 1]. It has dimension 4, and three of its bases are:

  • Monomials: 1,x,x2,x31, x, x^2, x^3.
  • Shifted Legendre: P~0=1\tilde P_0 = 1, P~1=2x−1\tilde P_1 = 2x - 1, P~2=6x2−6x+1\tilde P_2 = 6x^2 - 6x + 1, P~3=20x3−30x2+12x−1\tilde P_3 = 20x^3 - 30x^2 + 12x - 1. These are Legendre polynomials shifted from [−1,1][-1, 1] to [0,1][0, 1]; their key property, orthogonality, appears with inner products.
  • Bernstein: Bk,3(x)=(3k)xk(1−x)3−kB_{k,3}(x) = \binom{3}{k}x^k(1 - x)^{3-k}, namely (1−x)3(1-x)^3, 3x(1−x)23x(1-x)^2, 3x2(1−x)3x^2(1-x) and x3x^3. They are nonnegative on [0,1][0, 1] and sum to 1, and the coordinates ckc_k of pp in this basis are the ordinates of control points (k/3,ck)(k/3, c_k) of the graph of pp viewed as a Bézier curve, the curves used in typography and computer-aided design.

Why are these bases? Each contains 4 polynomials in a 4-dimensional space, so independence suffices (the “counting suffices” corollary). P~k\tilde P_k have degrees 0,1,2,30, 1, 2, 3 with nonzero leading coefficients: in a relation ∑akP~k=0\sum a_k\tilde P_k = 0, the coefficient of x3x^3 forces a3=0a_3 = 0, then that of x2x^2 forces a2=0a_2 = 0, and so on. For Bernstein, Bk,3B_{k,3} has at x=0x = 0 a zero of exactly order kk, and the same stepwise reasoning, now using the lowest power of xx, gives independence.

The same polynomial has very different coordinates in each basis. For p(x)=20x(x−12)(x−1)=20x3−30x2+10xp(x) = 20x(x - \tfrac12)(x - 1) = 20x^3 - 30x^2 + 10x:

[p]mon=(0,10,−30,20),[p]Leg=(0,−1,0,1),[p]Bern=(0,103,−103,0).[p]_{\text{mon}} = (0, 10, -30, 20), \qquad [p]_{\text{Leg}} = (0, -1, 0, 1), \qquad [p]_{\text{Bern}} = \big(0, \tfrac{10}{3}, -\tfrac{10}{3}, 0\big).

Check it: P~3−P~1=20x3−30x2+12x−1−(2x−1)=20x3−30x2+10x\tilde P_3 - \tilde P_1 = 20x^3 - 30x^2 + 12x - 1 - (2x - 1) = 20x^3 - 30x^2 + 10x.

InteractivePolynomials as vectors in R4\R^4
Base
  • p(x)p(x)
  • error band (δ=1.0 %\delta = 1.0\,\%)
Coordinates in this basis
0.00
10.00
−30.00
20.00
Initial polynomial
Sensitivity
1.0 %
Basec0c_0c1c_1c2c_2c3c_3amplif.
Monomials0.0010.00−30.0020.0062.4
Legendre0.00−1.000.001.002.1
Bernstein0.003.33−3.330.002.6
Worst error in pp with δ=1.0 %\delta = 1.0\,\% (monomial basis)0.600
Size of pp: max⁡[0,1]∣p∣\max_{[0,1]} \abs{p}0.96
amplif. =max⁡x∑k∣ckϕk(x)∣ / max⁡x∣p(x)∣= \max_x \sum_k \abs{c_k\phi_k(x)} \,/\, \max_x \abs{p(x)}: how much relative coordinate error can grow compared with pp.
The state is the polynomial, not its coordinates. Change basis: the blue curve stays put, but sliders jump to the new coordinates. The band shows worst-case error in pp if each coordinate has relative error δ\delta: compare all three bases for Cubic sine. Then enable Components in monomials: the view zooms out to show summands ckϕkc_k\phi_k, much larger than pp, which almost completely cancel.

In monomials, pp comes from adding three large terms, 10x10x, −30x2-30x^2 and 20x320x^3, which nearly cancel: the maximum of ∣p∣\abs{p} on [0,1][0, 1] is 5/(33)≈0.965/(3\sqrt3) \approx 0.96. A 1% relative error in each coordinate produces absolute errors 0.10.1, 0.30.3 and 0.20.2 in the summands, which no longer cancel, and error in pp can reach 0.60.6, over half its size. In Legendre or Bernstein, coordinates are small and the same 1% is barely visible: amplification falls from about 62 to about 2 or 3.

The effect worsens rapidly with degree. Functions x10x^{10} and x11x^{11} are almost indistinguishable on [0,1][0, 1] (their angle, sampled on a fine grid, is about 2.6°2.6°), so the high-degree monomial basis is a nearly dependent list. You will measure this in the libraries section and revisit it with polynomial interpolation and orthogonal polynomials in the numerical-methods module.

Beyond finite dimension

Not all spaces are finite-dimensional. The space P\mathcal{P} of all polynomials is not: a finite list of polynomials has a maximum degree dd, and xd+1x^{d+1} is outside its span. Since P\mathcal{P} is a subspace of C[a,b]C[a, b] and every subspace of a finite-dimensional space is finite-dimensional, C[a,b]C[a, b] is not finite-dimensional either.

In infinite dimensions “basis” branches into two notions. A Hamel basis is an independent set such that every vector is a finite combination of its elements. It exists in every vector space, but the proof needs Zorn’s lemma (indeed, every vector space having a basis is equivalent to the axiom of choice), and in spaces such as C[0,1]C[0, 1] it is uncountable and impossible to write down. Analysis uses something else: infinite expansions f=∑k≥0ckϕkf = \sum_{k \ge 0} c_k\phi_k converging in some norm, such as Fourier series in L2L^2. To discuss convergence we must measure distances, introduced with norms and inner products.

Independence in floating point

Everything above uses exact arithmetic. On a computer, “are they independent?” has two traps: exactly dependent data may cease to be so when represented in floating point, and independent data may be so close to dependence that the difference is noise.

[ ]A dependence the computer cannot seeBrowser
import numpy as np
import sympy as sp

v1 = np.array([0.1, 0.2, 0.3])
v2 = np.array([0.3, 0.6, 0.9])          # en aritmética exacta, v2 = 3 v1
print("3 * 0.1 == 0.3 ->", 3 * 0.1 == 0.3)
print("v2 - 3 v1 =", v2 - 3 * v1)

A = np.column_stack([v1, v2])
print("valores singulares:", np.linalg.svd(A, compute_uv=False))
print("matrix_rank(A, tol=0):", np.linalg.matrix_rank(A, tol=0))
print("matrix_rank(A):       ", np.linalg.matrix_rank(A))

exacta = sp.Matrix([[sp.Rational(1, 10), sp.Rational(3, 10)],
                    [sp.Rational(2, 10), sp.Rational(6, 10)],
                    [sp.Rational(3, 10), sp.Rational(9, 10)]])
print("rango exacto (SymPy): ", exacta.rank())

Decimals 0.10.1, 0.30.3, 0.60.6 and 0.90.9 cannot be represented exactly in binary, so stored v2 is not exactly three times stored v1. Moreover, SVD computes in floating point: it is backward stable, meaning its result is exact for a matrix perturbed on the order of ε∥A∥\eps\norm{\mat{A}}, with ε≈2.2⋅10−16\eps \approx 2.2 \cdot 10^{-16} machine epsilon, so a zero singular value is only guaranteed to come out on the order of ε σ1\eps\,\sigma_1, not 0. For both reasons the second singular value is on the order of 10−1610^{-16}, and exact comparison (tol=0) would declare the list independent. This is what you saw with Coplanar in the first interactive, where v1+v2\vb{v}_1 + \vb{v}_2 is also rounded on storage (2.42.4 is not representable either). NumPy gets it right by default because it uses a tolerance; the question is which one.

From-scratch implementation: pivot columns with relative tolerance

The elimination-based independence test translates directly into code. Traverse columns in order; a column is a pivot if, after subtracting combinations of earlier pivot columns, it retains a significant entry. Pivot columns form a basis of the span using vectors from the list itself, and the others are combinations of preceding ones. “Significant” must be relative to data scale: an absolute tolerance like 1e-10 means nothing if vectors have size 10−1210^{-12} or 10610^{6}.

[ ]Pivot columns by elimination with partial pivotingBrowser
def pivot_columns(A, rtol=1e-10):
    """Índices de las columnas pivote de A.

    La columna j es pivote si, tras eliminar con las columnas pivote
    anteriores, le queda alguna entrada mayor que rtol * max|A|.
    """
    R = np.array(A, dtype=float)              # copia: no modificamos A
    m, n = R.shape
    tol = rtol * np.abs(R).max() if R.size else 0.0
    pivots, row = [], 0
    for j in range(n):
        if row == m:                          # no caben más pivotes
            break
        i = row + np.argmax(np.abs(R[row:, j]))   # pivoteo parcial
        if abs(R[i, j]) <= tol:
            continue                          # (casi) dependiente
        R[[row, i]] = R[[i, row]]             # intercambio de filas
        R[row + 1:] -= np.outer(R[row + 1:, j] / R[row, j], R[row])
        pivots.append(j)
        row += 1
    return pivots

def is_independent(vectors, rtol=1e-10):
    A = np.column_stack(vectors)
    return len(pivot_columns(A, rtol)) == A.shape[1]

def basis_from_pivots(vectors, rtol=1e-10):
    """Subconjunto de `vectors` que es base de su envolvente."""
    piv = pivot_columns(np.column_stack(vectors), rtol)
    return [vectors[j] for j in piv]

e1, e2, e3 = np.eye(3)
print(pivot_columns(np.column_stack([e1, e2, e1 + e2, e3])))   # [0, 1, 3]
print(is_independent([v1, v2]), is_independent([e1, e2, e3]))

# contraste con NumPy en matrices aleatorias de rango conocido
rng = np.random.default_rng(0)
ok = 0
for _ in range(200):
    m, n, r = rng.integers(2, 8, size=3)
    r = min(r, m, n)
    # producto (m x r)(r x n): rango r con probabilidad 1
    A = rng.normal(size=(m, r)) @ rng.normal(size=(r, n))
    ok += len(pivot_columns(A)) == np.linalg.matrix_rank(A) == r
print(f"coinciden en {ok} de 200 casos")

Code indices start at 0: [0, 1, 3] are the first, second and fourth vectors in list (e1,e2,e1+e2,e3)(\vb{e}_1, \vb{e}_2, \vb{e}_1 + \vb{e}_2, \vb{e}_3).

Now construct a case where the answer depends on tolerance: a third vector that is the sum of the first two plus a perturbation of size η=10−9\eta = 10^{-9}.

[ ]The answer depends on toleranceBrowser
import matplotlib.pyplot as plt

rng = np.random.default_rng(1)
a, b, z = rng.normal(size=(3, 5))
V = np.column_stack([a, b, a + b + 1e-9 * z])
s = np.linalg.svd(V, compute_uv=False)
print("sigma_i / sigma_1 =", s / s[0])
for rtol in [1e-12, 1e-6]:
    print(f"rtol = {rtol:g}: pivot_columns -> {pivot_columns(V, rtol)},",
          f"matrix_rank -> {np.linalg.matrix_rank(V, tol=rtol * s[0])}")

etas = np.logspace(-17, 0, 60)
ratio = []
for eta in etas:
    Ve = np.column_stack([a, b, a + b + eta * z])
    s = np.linalg.svd(Ve, compute_uv=False)
    ratio.append(s[-1] / s[0])
plt.loglog(etas, ratio, label=r"$\sigma_3/\sigma_1$")
plt.axhline(5 * np.finfo(float).eps, ls="--", color="gray",
            label="tolerancia por defecto de NumPy")
plt.axhline(1e-6, ls=":", color="k", label=r"$\tau = 10^{-6}$")
plt.xlabel(r"tamaño de la perturbación $\eta$")
plt.ylabel(r"$\sigma_3/\sigma_1$")
plt.legend()
plt.title("La dependencia es una cuestión de grado")
plt.show()

The graph summarizes the section: σ3/σ1\sigma_3/\sigma_1 grows in proportion to η\eta until, below 10−1610^{-16}, it reaches the rounding floor. Each tolerance is a horizontal line, and the rank obtained depends on which side of the line you fall. There is no universally correct tolerance: the right one corresponds to error in your data.

Why SVD rather than pivots or determinant? Because σmin⁡\sigma_{\min} has an exact meaning: it is the spectral-norm distance from V\mat{V} to the nearest matrix with dependent columns. This is the Eckart–Young theorem, proved later, and why σmin⁡/σmax⁡\sigma_{\min}/\sigma_{\max} is the relative distance to dependence. Neither pivot size nor determinant has that property, as the next matrix shows starkly.

[ ]Pivots and determinant can misleadBrowser
n = 30
T = np.eye(n) - np.triu(np.ones((n, n)), 1)  # 1 diagonal, -1 encima
print("columnas pivote:", len(pivot_columns(T, 1e-6)), "de", n)
print("det(T) =", np.linalg.det(T))
s = np.linalg.svd(T, compute_uv=False)
print("sigma_min / sigma_max =", s[-1] / s[0])
print("rango con rtol = 1e-6:", np.linalg.matrix_rank(T, tol=1e-6 * s[0]))

E = np.zeros((n, n))
E[-1, 0] = -2.0 ** (2 - n)    # cambiar UNA entrada en unos 4e-9
print("|E| =", 2.0 ** (2 - n), " det(T + E) =", np.linalg.det(T + E))

Every pivot is 1, as is the determinant, yet changing one entry by 2−28≈3.7⋅10−92^{-28} \approx 3.7 \cdot 10^{-9} makes the matrix exactly singular. Vector x=(2n−2,2n−3,…,2,1,1)\vb{x} = (2^{n-2}, 2^{n-3}, \dots, 2, 1, 1) satisfies Tx=en\mat{T}\vb{x} = \vb{e}_n, and the perturbation cancels precisely that component. Elimination, examining columns one by one against preceding ones, misses a collective near-dependence. SVD sees it.

Scale matters. Ratio σmin⁡/σmax⁡\sigma_{\min}/\sigma_{\max} measures distance to dependence relative to the norm of the whole matrix. But independence does not change when a vector is multiplied by a nonzero scalar, while the ratio does: a tiny vector, even perpendicular to the rest, gives a tiny σmin⁡\sigma_{\min}. Check the first interactive with Short but perpendicular: σ3/σ1≈0.009\sigma_3/\sigma_1 \approx 0.009, almost the same as Nearly coplanar, but ν≈1\nu \approx 1. If data error is relative to each vector (each measurement has its own 1%), normalize columns first, exactly as ν\nu does.

[ ]Scaling a vector changes the ratio, not independenceBrowser
def cociente(M):
    s = np.linalg.svd(M, compute_uv=False)
    return s[-1] / s[0]

W = np.random.default_rng(0).normal(size=(5, 3))
Ws = W * np.array([1.0, 1.0, 1e-4])    # misma envolvente, tercer vector diminuto
Wn = Ws / np.linalg.norm(Ws, axis=0)   # columnas normalizadas
for nombre, M in [("original", W), ("escalada", Ws), ("normalizada", Wn)]:
    print(f"{nombre:12s} sigma_3/sigma_1 = {cociente(M):.1e}")

With τ=10−4\tau = 10^{-4}, the scaled matrix would be declared rank 2 even though its three vectors are well separated in angle; normalized, the ratio returns to the order of 0.10.1. This is what test_escala checks in the next exercise, and why pivot_columns, whose tolerance is relative to max⁡∣A∣\max\abs{\mat{A}} rather than each column, does not work there.

In exact arithmetic independence is yes or no; in floating point it is a quantity, the relative distance to dependence σmin⁡/σmax⁡\sigma_{\min}/\sigma_{\max} of vectors scaled to their errors, and the decision compares it to data error.

CodeBasis of a span
Implement basis_of_span(vectors, tol) to traverse vectors in order and accept each v if its distance to the span of those already accepted exceeds tol * ||v|| (distance relative to the vector itself). Return accepted indices in order, starting at 0 as in Python. For distance you can use least squares: np.linalg.lstsq(A, v, rcond=None) gives coefficients of the combination of columns of A closest to v. Never accept the zero vector.
import numpy as np

def basis_of_span(vectors, tol=1e-10):
  """Índices (en orden) de los vectores que forman una base."""
  chosen = []
  # recorre los vectores; acepta v si su distancia a la envolvente
  # de los ya aceptados es mayor que tol * ||v||
  return chosen
Shift+Enter to run

When finished, try it on the columns of earlier matrix T\mat{T}, basis_of_span(list(T.T), tol=1e-6): it accepts all of them, because column jj is at relative distance 1/j≥1/301/\sqrt{j} \ge 1/\sqrt{30} from its predecessors. No greedy method examining vectors in order detects that collective near-dependence; SVD does.

The professional version

In practice you will not write pivot_columns; you will use these tools, and it helps to know what each does internally.

  • Numerical rank. np.linalg.matrix_rank(A) counts σi\sigma_i exceeding a threshold, by default σ1max⁡(m,n) ε\sigma_1 \max(m, n)\,\eps, with ε\eps machine epsilon.
  • Orthonormal basis of the span. scipy.linalg.orth(A) returns left singular vectors associated with non-negligible σi\sigma_i. They are not a subset of your columns.
  • Dependence relations. scipy.linalg.null_space(A) also uses SVD to give a basis of {a:Aa=0}\{\vb{a} : \mat{A}\vb{a} = \vb{0}\}: each vector is a relation ∑iaivi=0\sum_i a_i\vb{v}_i = \vb{0}.
  • A subset of columns forming a basis. scipy.linalg.qr(A, pivoting=True), QR with column pivoting, is more reliable than elimination because each step chooses the column with the largest component outside the span of those already chosen. It works very well in practice, although counterexamples exist (the Kahan matrix); rank-revealing QR (RRQR) variants provide guarantees.
  • Exact arithmetic. sympy.Matrix(A).rref() gives reduced row echelon form (RREF) and pivot columns using rational numbers, without rounding.

Two API details often cause trouble. In matrix_rank, parameter tol is an absolute singular-value threshold; since NumPy 2.0, rtol specifies it relative to σ1\sigma_1. And orth returns a basis of the span, but not one made of your vectors: if you need to know which vectors to retain (for example, which linear-model features are redundant), you want pivot columns, and the robust tool is QR with column pivoting.

[ ]Rank, dependence relations and pivot columns with librariesBrowser
import scipy.linalg as sla

V = np.column_stack([e1, e2, e1 + e2, e3])
print("rango:", np.linalg.matrix_rank(V))
print("orth: base ortonormal de forma", sla.orth(V).shape)
N = sla.null_space(V)
# v1 + v2 - v3 = 0, normalizada para que el primer coeficiente sea 1
print("relación de dependencia:", (N[:, 0] / N[0, 0]).round(12))
_, _, piv = sla.qr(V, pivoting=True)
print("QR con pivoteo, orden:", piv, "-> base:", sorted(piv[:3].tolist()))
R, pivotes = sp.Matrix(V.astype(int)).rref()
print("SymPy, columnas pivote exactas:", pivotes)

Pivoted QR chooses a different basis from elimination: it begins with the longest column, e1+e2\vb{e}_1 + \vb{e}_2. Bases are not unique; dimension is.

For polynomials, numpy.polynomial implements each basis as a class, and convert changes coordinates. Argument domain=[0, 1] shifts Legendre polynomials from [−1,1][-1, 1] to [0,1][0, 1], exactly our P~k\tilde P_k.

[ ]Polynomial coordinates in monomial and Legendre basesBrowser
from numpy.polynomial import Polynomial, Legendre

p = Polynomial([0, 10, -30, 20])              # 20x(x - 1/2)(x - 1)
pL = p.convert(kind=Legendre, domain=[0, 1])  # el mismo, en Legendre
print("coordenadas en monomios:", p.coef)
print("coordenadas en Legendre:", np.round(pL.coef, 12) + 0.0)
x = np.linspace(0, 1, 7)
print("mismo polinomio:", np.allclose(p(x), pL(x)))

Finally, each basis’s sensitivity as degree increases. If you sample basis functions on a grid of [0,1][0, 1] and put them as columns of a matrix, its condition number measures how close the basis is to dependence.

[ ]How close each basis gets to dependence as degree growsBrowser
from numpy.polynomial import polynomial as P, legendre as L
from math import comb

xs = np.linspace(0, 1, 200)
grados = list(range(1, 21))
cond = {"monomios": [], "Legendre": [], "Bernstein": []}
for n in grados:
    cond["monomios"].append(np.linalg.cond(P.polyvander(xs, n)))
    cond["Legendre"].append(np.linalg.cond(L.legvander(2 * xs - 1, n)))
    Bn = np.column_stack([comb(n, k) * xs**k * (1 - xs)**(n - k)
                          for k in range(n + 1)])
    cond["Bernstein"].append(np.linalg.cond(Bn))

for nombre, c in cond.items():
    plt.semilogy(grados, c, marker="o", ms=3, label=nombre)
plt.xlabel("grado n")
plt.ylabel("número de condición de la base en [0, 1]")
plt.legend()
plt.title("Las bases no son igual de estables")
plt.show()
print({k: f"{v[-1]:.1e}" for k, v in cond.items()})

At degree 20, the monomial basis has a condition number near 101510^{15}: it is a step away from numerical dependence and any fit in it loses almost all digits. Legendre remains below 10. Bernstein is in between under this global measure, although it is the most stable nonnegative basis for evaluation with perturbed coefficients (Farouki and Goodman’s note): “stable” always means stable for a particular task.

Common mistakes

Exercises

QuizIs it a vector space?
Which of these structures are real vector spaces?

More than one answer may be correct.

ProofIntersection and union
Prove: If UU and WW are subspaces of VV, then U∩WU \cap W is a subspace; by contrast U∪WU \cup W is one only when either contains the other. Even a finite union of proper subspaces cannot fill Rn\R^n.
0
Use the subspace criterion: show that 0∈U∩W\vb{0} \in U \cap W and U∩WU \cap W is closed under linear combinations.

Step 1 of 5. Why is 0∈U∩W\vb{0} \in U \cap W?

QuizSubspace or not?
Which of these sets are subspaces of R3\R^3?

More than one answer may be correct.

QuizSubspaces without arrows
Which sets are subspaces of their containing space?

More than one answer may be correct.

QuizPositive reals
In V=R>0V = \R_{>0} with x⊞y=xyx \boxplus y = xy and λ⊡x=xλ\lambda \boxdot x = x^\lambda, what is dim⁡V\dim V and which list is a basis?
NumericZero trace
What is the dimension of the space of real 3×33 \times 3 matrices with zero trace?
NumericInevitable intersections
Three subspaces U,W,X⊆R1024U, W, X \subseteq \R^{1024} each have dimension 800. What is the smallest possible dimension of U∩W∩XU \cap W \cap X?
Numeric$x^3$ in Legendre
The coordinates of x3x^3 in the Legendre basis (P~0,P~1,P~2,P~3)(\tilde P_0, \tilde P_1, \tilde P_2, \tilde P_3) shifted to [0,1][0, 1] are (c0,c1,c2,c3)(c_0, c_1, c_2, c_3). Calculate c1c_1.
QuizWhat guarantees independence?
Which conditions guarantee that a list (v1,…,vk)(\vb{v}_1, \dots, \vb{v}_k) of vectors in Rn\R^n is linearly independent?

More than one answer may be correct.

QuizIndependent functions
Which lists of functions are linearly independent in the indicated space?

More than one answer may be correct.

QuizHow many directions?
You measure three similarly sized vectors with relative error on the order of 10−610^{-6}, and the SVD of V=[v1 v2 v3]\mat{V} = [\vb{v}_1\ \vb{v}_2\ \vb{v}_3] gives σ=(3.1, 1.2, 4⋅10−11)\sigma = (3.1,\ 1.2,\ 4 \cdot 10^{-11}). Which conclusion and justification are correct?

Summary

  • A vector space is any set with addition and scalar multiplication satisfying eight axioms; lists, matrices, polynomials, functions and images are examples, and anything proved from the axioms applies to all.
  • A subspace is recognized by three checks: it contains 0\vb{0} and is closed under addition and scalars. Shifted lines, unions, half-planes and bounded-rank matrices are not subspaces.
  • A list is independent if no nontrivial combination yields 0\vb{0} or, equivalently, if each vector in its span has a unique representation.
  • The Steinitz exchange lemma proves that an independent list is never longer than a spanning list; all bases therefore have the same length and dimension is well defined. With it come Grassmann’s formula, which forces large subspaces to intersect, and a complement, which always exists but is not unique.
  • A basis turns each vector into a list of coordinates. Different bases give different coordinates, and some amplify errors much more than others.
  • In floating point independence is a quantity: σmin⁡/σmax⁡\sigma_{\min}/\sigma_{\max} of vectors scaled to their errors, compared with data error.
Key idea
There are many bases, and a basis is a choice; dimension is unique and a fact.