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 pixels is a function from the pixel grid to , and the average of two images is another image. The update 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.
- Economy. Each theorem is proved once and applies to lists, polynomials, matrices, functions and any example that appears tomorrow.
- Dimension. A number measures how many independent pieces of information are needed to describe an object. Polynomials of degree 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.
- 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 , with and much smaller than the total number of parameters, and call the smallest 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 is the set of all their linear combinations . In , 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.
Three observations from the experiment are useful before formalizing anything.
A vector already in the span of the others adds nothing. With Coplanar, 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 is (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
which is 1 if the vectors are pairwise perpendicular and 0 if they are dependent ( is Hadamard’s inequality).
The boundary is blurred. With Nearly coplanar, lies at distance from the plane of and . In exact arithmetic the three vectors are independent, but if their coordinates come from measurements with error , the third direction is noise. The lower strip shows relative singular values , studied in depth with the SVD: the computer counts directions exceeding a tolerance , and raising above changes the answer. Even exact dependence is not immune: with Coplanar, is not 0 but about , and with 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 and scalar multiplication must lie in . This closure is the condition that most often fails in examples.
Examples you will use daily:
| Space | Vectors | Operations | Zero |
|---|---|---|---|
| lists | componentwise | ||
| matrices | entrywise | zero matrix | |
| polynomials of degree | coefficientwise | zero polynomial | |
| continuous functions on | pointwise | function | |
| functions , with any set | pointwise | zero function |
The last includes the others. A list of is a function ; a matrix of , a function ; a sequence, a function ; an image of , a vector of . In addition and multiplication are defined pointwise, and , and all eight axioms are inherited from those of at each point. Thus an activation tensor of shape is simply a vector in , which is 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 being the identity .
Proof
If and are identities, . If and are inverses of , then . For :
The same trick with gives . Finally, , so is an inverse of and, by uniqueness, is .
∎Subspaces
Almost all vector spaces encountered in practice live inside a larger one: solutions of a homogeneous system inside , symmetric matrices inside , polynomials inside continuous functions. For these there is no need to check all eight axioms.
Proof
If is a subspace, (ii) and (iii) express closure of its operations. For (i), the identity of satisfies in ; adding gives . Conversely, if (i), (ii) and (iii) hold, the operations are well-defined in ; axioms 1, 2 and 5–8 are equalities holding in and therefore in ; the identity is present by (i); and the inverse of is by (iii) and the previous proposition. In the equivalent form, suffices instead of (i): if , then .
∎Examples of subspaces, all by the same one-line argument:
- and (the trivial ones); lines and planes in through the origin.
- The solution set of a homogeneous system , because . This is the null space (or kernel) of . Note: in kernel methods, kernel means something else, a similarity function.
- The span of any set : it is a subspace and the smallest containing , because every subspace containing contains all its combinations.
- ; symmetric, upper-triangular and zero-trace matrices within .
- and, within , the solution set of differential equation .
And counterexamples worth keeping in mind:
- A hyperplane not passing through the origin, with (a line in ): it does not contain . It is an affine subspace, a translated subspace , like in the motivation.
- The union of two lines through the origin: closed under scalar multiplication, but not addition.
- A half-plane : closed under addition and nonnegative scalars (a convex cone), but not .
- The probability simplex : it neither contains nor is closed under addition.
- Matrices of rank , with : closed under scalars, but has rank although each summand has rank . Thus the set of LoRA updates , with of 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- LoRA updates guarantees only rank , which matters when merging them.
Intersection, union and sum
The intersection of subspaces is a subspace. Their union almost never is: is a subspace only when one contains the other. You will prove both in the exercises. The correct substitute for union is the sum
the smallest subspace containing both. When the sum is direct, , and each vector in decomposes uniquely: if , then .
For more than two summands, the correct condition is that each intersects the sum of the others only in (after Grassmann’s formula you will see this is equivalent to ). Trivial pairwise intersections are insufficient: three distinct lines in through the origin intersect pairwise only in , and their sum, , 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 (), and order will matter when we discuss coordinates. The three readings of the definition are equivalent and useful to know.
Proof
(1 ⇔ 2) If , then is a nontrivial relation (the coefficient of is ). Conversely, if with some , rearranging gives .
(1 ⇒ 3) If , subtraction gives , and independence gives . (3 ⇒ 1) is a representation of ; by uniqueness, any combination equal to 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 and let be the largest index with . Then (if , this says , which lies in ). Any combination of the full list becomes one without by replacing with that expression, so the span is unchanged.
∎The test in . If vectors are columns of , a combination is the product . The list is independent if and only if the homogeneous system has only the trivial solution, that is, if Gaussian elimination leaves a pivot in every column. If there are more unknowns than equations, a variable is free and the list is dependent: holds at most independent vectors. This is a special case of the next section’s exchange lemma.
Outside the test is the same, but the equation lives in a function space:
- is independent: if for every , the polynomial has infinitely many roots and all coefficients are zero (or, differentiating times at , ).
- is independent in : from for every , evaluating at gives , and at gives .
- is dependent: . Very different-looking functions can be dependent.
The exchange lemma and dimension
Intuitively, 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 into the spanning list one at a time and, each time, remove one in exchange while keeping the list spanning . If we ran out of to remove, the incoming would be a combination of the preceding , contradicting independence.
The proof is collapsed: before opening it, try the guided version.
Step 1 of 5. Why does the base case hold?
Proof
We prove by induction on the claim
: and, after reordering , list spans .
is the hypothesis. Suppose with . Since ,
If all were zero (in particular, if and no remained), we would have , a nontrivial relation among (the coefficient of is 1), contradicting independence (a proof by contradiction). Thus some , which in particular requires . Reorder, suppose and rearrange:
Thus is a combination of , and the remaining vectors of are in . Therefore , which is . With we obtain 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 is dependent, that representation is not unique, and with zero coefficient in one can have a nonzero coefficient in another; the coefficient belongs to the representation, not the vector. The intermediate list need not be independent; only its spanning of is preserved, and that invariant plus independence of suffices. When there are several candidates, choosing the largest is the same idea as partial pivoting in Gaussian elimination: divide by the largest available coefficient.
Bases and dimension
Proof
Let and be bases with and elements. is independent and spans, so by the exchange lemma. Reversing their roles gives .
∎Without the exchange lemma this definition would make no sense: bases could have different lengths. The edge case fits too: the basis of is the empty list (independent by convention, with span ), so .
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 . (2) Let be independent and spanning. Go through and add each one outside the current span. Adding a vector outside the span of an independent list preserves independence (if appeared in a relation with nonzero coefficient, it could be isolated and would be in the span). At the end, all are in the list’s span, which therefore spans .
∎Proof
(1) is the exchange lemma applied against a basis. (2) An independent list of length extends to a basis with elements, so nothing is added: it was already a basis. A spanning list of length reduces to a basis of elements, so nothing is removed. (3) We do not yet know is finite-dimensional, so construct a basis by hand: start with the empty list and, while it does not span , add a vector of outside its span. The list remains independent (by the preceding proposition) and is an independent list in , so it never exceeds vectors: the process stops in at most steps, and stops only when the list spans . It is a basis of , so . If , a basis of is an independent list of vectors in , so by (2) it is a basis of and .
∎Proof
By (3), has a basis . Extend it to a basis of and take . Every vector in is a combination of that basis, hence lies in . If , then ; subtracting, basis independence gives , that is, .
∎The complement is not unique: in , any line through the origin other than complements line . The same construction, extending a subspace basis to one of the entire space, proves the rank–nullity theorem.
Proof
Let be a basis of . Extend it to a basis of and a basis of . List spans . It is independent: if , vector lies in both and , hence in , and can be written . Since is independent, all (and ) are zero; remains, and independence of makes the rest zero. Thus .
∎The formula has a useful high-dimensional consequence: two large subspaces cannot avoid each other. Two planes through the origin in intersect in at least a line, because . In a 768-dimensional embedding space, two 500-dimensional subspaces share at least dimensions.
For two summands the formula also characterizes direct sum: if and only if , that is, if and only if . The version with more summands is the one announced in the subspaces section.
Proof
Concatenate a basis of each . The resulting list spans the sum and has vectors, so equality of dimensions is equivalent to independence of (if dependent, it could be reduced to a shorter basis). If is dependent, group a nontrivial relation by blocks: with , and some is nonzero because each block is independent; that lies in and in the sum of the others. Conversely, if an of is with , expanding each term in its basis gives a relation among the vectors of with some nonzero coefficient in block .
∎Some dimensions worth memorizing:
| Space | Basis | Dimension |
|---|---|---|
| standard | ||
| matrices with a 1 at | ||
| symmetric matrices | and with | |
| antisymmetric matrices | with | |
| solutions of |
Bases and coordinates
A basis is exactly what is needed to turn an abstract vector into a list of numbers.
The map is bijective and respects operations: and (add the representations and use uniqueness). It is an isomorphism, a bijective linear map: every real space of dimension is isomorphic to , 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: 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 means solving a system. If , equation is , so . For example, with and , coordinates of come from and : . The code solves the system; it never computes the inverse (the next lesson explains why when introducing the matrix inverse).
The interactive teaches two things. The first is geometric: takes the distorted basis grid to the standard grid, and coordinates are simply the position of on that grid. The second is numerical and most important to an engineer. When and are nearly parallel, the basis remains a basis in exact arithmetic, but a small error in becomes a huge error in : a disk of radius becomes an ellipse whose major semiaxis is . The ratio is the condition number, which throughout the module measures error amplification.
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 in moves each coordinate by a whole unit, and the coordinate vector : a factor of about 1400, close to the worst-case bound .
Polynomials: three bases for the same space
An example where basis choice really matters is , polynomials of degree on . It has dimension 4, and three of its bases are:
- Monomials: .
- Shifted Legendre: , , , . These are Legendre polynomials shifted from to ; their key property, orthogonality, appears with inner products.
- Bernstein: , namely , , and . They are nonnegative on and sum to 1, and the coordinates of in this basis are the ordinates of control points of the graph of 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). have degrees with nonzero leading coefficients: in a relation , the coefficient of forces , then that of forces , and so on. For Bernstein, has at a zero of exactly order , and the same stepwise reasoning, now using the lowest power of , gives independence.
The same polynomial has very different coordinates in each basis. For :
Check it: .
In monomials, comes from adding three large terms, , and , which nearly cancel: the maximum of on is . A 1% relative error in each coordinate produces absolute errors , and in the summands, which no longer cancel, and error in can reach , 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 and are almost indistinguishable on (their angle, sampled on a fine grid, is about ), 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 of all polynomials is not: a finite list of polynomials has a maximum degree , and is outside its span. Since is a subspace of and every subspace of a finite-dimensional space is finite-dimensional, 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 it is uncountable and impossible to write down. Analysis uses something else: infinite expansions converging in some norm, such as Fourier series in . 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.
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 , , and 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 , with machine epsilon, so a zero singular value is only guaranteed to come out on the order of , not 0. For both reasons the second singular value is on the order of , and exact comparison (tol=0) would declare the list independent. This is what you saw with Coplanar in the first interactive, where is also rounded on storage ( 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 or .
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 .
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 .
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: grows in proportion to until, below , 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 has an exact meaning: it is the spectral-norm distance from to the nearest matrix with dependent columns. This is the Eckart–Young theorem, proved later, and why is the relative distance to dependence. Neither pivot size nor determinant has that property, as the next matrix shows starkly.
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 makes the matrix exactly singular. Vector satisfies , 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 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 . Check the first interactive with Short but perpendicular: , almost the same as Nearly coplanar, but . If data error is relative to each vector (each measurement has its own 1%), normalize columns first, exactly as does.
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 , 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 . This is what test_escala checks in the next exercise, and why pivot_columns, whose tolerance is relative to 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 of vectors scaled to their errors, and the decision compares it to data error.
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 chosenWhen finished, try it on the columns of earlier matrix , basis_of_span(list(T.T), tol=1e-6): it accepts all of them, because column is at relative distance 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 exceeding a threshold, by default , with machine epsilon. - Orthonormal basis of the span.
scipy.linalg.orth(A)returns left singular vectors associated with non-negligible . They are not a subset of your columns. - Dependence relations.
scipy.linalg.null_space(A)also uses SVD to give a basis of : each vector is a relation . - 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 . 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.
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, . 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 to , exactly our .
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 and put them as columns of a matrix, its condition number measures how close the basis is to dependence.
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 : 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
More than one answer may be correct.
Step 1 of 5. Why is ?
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be 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 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 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: of vectors scaled to their errors, compared with data error.