The smallest rank for a threshold
rank_for_energy(s, 0.95) returns the smallest rank whose retained energy reaches the target, using np.searchsorted on the cumulative energy curve.
The test’s known spectrum is [5, 3, 1, 0]: squares 25, 9, 1, 0, total 35. Retained energy is 25/35 at rank 1 and 34/35 at rank 2, so the smallest rank meeting 95% is 2 — and the reconstruction error there is at most 5%.
No fixed rank guarantees 95% energy for every image; the smallest rank meeting a threshold depends on the data.