Mathematical Foundations

VIII.9 · Numerical Computing

Which element does an array shape tell you to use?

Align trailing dimensions and inspect every output element’s source indices. Compare scalars, vectors, matrices, batched arrays and empty axes, then reduce an explicitly chosen output axis.

Inspect broadcasting through actual element indices

Elementwise operation

(2,3) + (3,): valid. Trailing dimensions agree or one broadcasts. Reduction over 1 gives shape (2,). Arrays use explicit zero-based axes and row-major indexing. This is computational array vectorization, distinct from geometric vectors; operation counts do not predict wall-clock speed.

Left shape
(2,3)
Right shape
(3,)
Mathematical output shape
(2,3)
Broadcasting classification
valid
Actual elementwise operations in this bounded model
6
Reduction output shape
(2,)

= exact rationals or classifications · ≈ a formatted numerical display. Exceptional values retain their stated meaning.

Ci=AπA(i)+BπB(i)C_{\mathbf i}=A_{\pi_A(\mathbf i)}+B_{\pi_B(\mathbf i)}
Rj=∑k along chosen axisCi(j,k)R_{\mathbf j}=\sum_{k\ \mathrm{along\ chosen\ axis}}C_{\mathbf i(\mathbf j,k)}
Align trailing axes; missing leading axes have size one.
output axisleft sizeright sizecompatible
021true
133true
Actual output values and the exact source index mapping.
output indexleft indexright indexleft valueright valueresult
(0,0)(0,0)(0,)11011
(0,1)(0,1)(1,)21113
(0,2)(0,2)(2,)31215
(1,0)(1,0)(0,)41014
(1,1)(1,1)(1,)51116
(1,2)(1,2)(2,)61218
Reduce actual output elements; remove the chosen axis, with empty sums equal to zero.
reduced indexcontributing output indicesexact sum
(0,)(0,0) + (0,1) + (0,2)39
(1,)(1,0) + (1,1) + (1,2)48

Align trailing axes

Missing leading axes behave as size one. Equal sizes or a size-one axis are compatible; zero with one produces zero length.

Inspect the recorded values\text{Inspect the recorded values}
Actual intermediate values; = exact rationals, ≈ binary64 displays.
quantityvalue
leftShape(2,3)
rightShape(3,)
classificationvalid
reasonTrailing dimensions agree or one broadcasts.

() scalar, (3,) vector, (2,3) matrix; at most four axes of size 0–4 and 64 input/output elements.

Shapes align from the last axis; a size-one axis broadcasts, including against an empty axis.

Zero-based axis, a negative index from the end, or all. Invalid axes are shown explicitly.

from −10 to 10, whole numbers only

from −10 to 10, whole numbers only

Edit bounded shapes and inspect actual source/output index mappings, elementwise values and axis reductions; invalid pairs have explicit reasons.

Intuition: shape describes a collection of positions

An array shape says how many positions exist along each axis. A scalar has shape (), a vector-shaped array has one axis, a matrix has two, and a batched array adds leading axes. The shape participates in the operation; it is not merely a label attached afterward.

Computational vectorization expresses a collection of operations through array primitives. It does not mean that every array represents a directed displacement in a geometric space. This explorer focuses on index correspondence: for each output position, identify exactly which positions of the two inputs supplied its values.

Values are bounded consecutive integers in row-major order, beginning at the two selected starts. This keeps the hand calculations exact while exposing shape mechanics. Later real floating-point arrays retain their numerical issues even when the shape operation is valid.

Definition: trailing-axis broadcasting

Align shapes from the last axis. Missing leading axes behave as length one. At each aligned axis, the sizes must be equal, or one must be one. A size-one input axis reuses index zero at every output position on that axis.

The output size at an aligned axis is the shared size when equal, or the other size when one side is one. This distinction matters for empty dimensions: zero with one produces zero length, not length one. Zero with a different nonunit size is incompatible.

This bounded explorer supports at most four axes, sizes 0–4, and at most 64 elements in each input and output. A compatible output beyond that limit is labelled as mathematically compatible but outside the demonstration bound. It is distinct from an incompatible pair.

Mechanics: indices, operations and reductions

The source-index table shows each output index, its left input index, its right input index, both values and the exact elementwise result. Addition and multiplication operate on those selected elements. They are not matrix multiplication, contraction or dot product.

Reduce a zero-based output axis by summing its actual values and removing that axis from the shape. Negative axis indices count from the end; all reduces every axis to a scalar. An empty sum is zero. Invalid axes remain explicit: a scalar has no explicit axis in this teaching contract, although all can reduce it to itself.

Shape syntax and allocation bounds are validated before any output construction. Valid inputs with incompatible shapes remain available to inspect; the operation has no output values, rather than a silently repaired shape.

Derivation: the index projection

Let the output multi-index be i\mathbf i. For each input, define a projection that drops missing leading axes and replaces every size-one axis index by zero. The elementwise addition is then

Ci=AπA(i)+BπB(i).C_{\mathbf i}=A_{\pi_A(\mathbf i)}+B_{\pi_B(\mathbf i)}.

For shapes (2,3) and (3,), the right shape behaves like (1,3), giving

Cij=Aij+Bj,i=0,1; j=0,1,2.C_{ij}=A_{ij}+B_j,\qquad i=0,1;\ j=0,1,2.

The right vector is reused across rows. In (2,3)+(2,), the final sizes are 3 and 2: neither is one, so no such output correspondence exists.

Reducing axis one of a 2×3 output yields

Ri=∑j=02Cij.R_i=\sum_{j=0}^{2}C_{ij}.

The result has shape (2,), not (2,1); this chapter does not keep a removed dimension as an extra size-one axis.

Worked examples: actual values and batched reuse

The canonical left matrix is [[1,2,3],[4,5,6]], while the right vector is [10,11,12]. Broadcasting produces [[11,13,15],[14,16,18]]. At output [1,1], left [1,1] contributes 5 and right [1] contributes 11, so the result is exactly 16.

Reducing axis one produces [39,48]. Reducing axis zero instead produces [25,29,33]. The shape identifies which positions are combined; summing all positions would instead produce the scalar 87.

In the batched preset, (2,1,3)+(1,4,1) produces (2,4,3). The left input is reused along the middle axis; the right is reused along batch and final axes. Reducing the final axis produces shape (2,4) and values [[36,39,42,45],[45,48,51,54]].

For (0,3)+(1,3), the output has shape (0,3) and contains no elements. Reducing axis zero yields three exact zeros, one empty sum per remaining column. Empty arrays are valid shapes under this bounded policy, not fabricated data.

Worked example: Inspect broadcasting through actual element indices

(2,3) + (3,): valid. Trailing dimensions agree or one broadcasts. Reduction over 1 gives shape (2,). Arrays use explicit zero-based axes and row-major indexing. This is computational array vectorization, distinct from geometric vectors; operation counts do not predict wall-clock speed.

Left shape
(2,3)
Right shape
(3,)
Mathematical output shape
(2,3)
Broadcasting classification
valid
Actual elementwise operations in this bounded model
6
Reduction output shape
(2,)

= exact rationals or classifications · ≈ a formatted numerical display. Exceptional values retain their stated meaning.

Ci=AπA(i)+BπB(i)C_{\mathbf i}=A_{\pi_A(\mathbf i)}+B_{\pi_B(\mathbf i)}
Rj=∑k along chosen axisCi(j,k)R_{\mathbf j}=\sum_{k\ \mathrm{along\ chosen\ axis}}C_{\mathbf i(\mathbf j,k)}
Align trailing axes; missing leading axes have size one.
output axisleft sizeright sizecompatible
021true
133true
Actual output values and the exact source index mapping.
output indexleft indexright indexleft valueright valueresult
(0,0)(0,0)(0,)11011
(0,1)(0,1)(1,)21113
(0,2)(0,2)(2,)31215
(1,0)(1,0)(0,)41014
(1,1)(1,1)(1,)51116
(1,2)(1,2)(2,)61218
Reduce actual output elements; remove the chosen axis, with empty sums equal to zero.
reduced indexcontributing output indicesexact sum
(0,)(0,0) + (0,1) + (0,2)39
(1,)(1,0) + (1,1) + (1,2)48

Align trailing axes

Missing leading axes behave as size one. Equal sizes or a size-one axis are compatible; zero with one produces zero length.

Inspect the recorded values\text{Inspect the recorded values}
Actual intermediate values; = exact rationals, ≈ binary64 displays.
quantityvalue
leftShape(2,3)
rightShape(3,)
classificationvalid
reasonTrailing dimensions agree or one broadcasts.

Select the recorded intermediate values. Previous, next and direct replay navigation preserve immutable numerical history.

Executable reference code

The pedagogical program uses Cartesian products and indexed dictionaries to select elements under the broadcasting rule. The NumPy version uses actual array broadcasting and axis sums and checks their literal values and shapes. Use the Cartesian construction to check the NumPy shapes and values, including scalar, batched and empty-axis examples.

code/python/vectorized_computation.py
"""Cartesian index dictionaries expose trailing-axis broadcasting without a tensor backend."""
from itertools import product
from math import prod
def indices(shape):
    assert len(shape)<=4 and all(0<=d<=4 for d in shape) and prod(shape)<=64
    return list(product(*(range(d) for d in shape)))
def broadcast(a_shape,b_shape,a_start=1,b_start=10):
    rank=max(len(a_shape),len(b_shape));left=(1,)*(rank-len(a_shape))+a_shape;right=(1,)*(rank-len(b_shape))+b_shape
    if any(a!=b and a!=1 and b!=1 for a,b in zip(left,right)):
        raise ValueError('incompatible trailing dimensions')
    shape=tuple(b if a==1 else a for a,b in zip(left,right))
    assert prod(shape)<=64
    a=dict(zip(indices(a_shape),range(a_start,a_start+prod(a_shape))))
    b=dict(zip(indices(b_shape),range(b_start,b_start+prod(b_shape))))
    result={}
    for index in indices(shape):
        ai=tuple(0 if d==1 else index[rank-len(a_shape)+i] for i,d in enumerate(a_shape))
        bi=tuple(0 if d==1 else index[rank-len(b_shape)+i] for i,d in enumerate(b_shape))
        result[index]=a[ai]+b[bi]
        print('output',index,'left',ai,a[ai],'right',bi,b[bi],'value',result[index])
    return shape,result
if __name__=='__main__':
    shape,result=broadcast((2,3),(3,))
    assert shape==(2,3) and list(result.values())==[11,13,15,14,16,18]
    assert [sum(value for (row,col),value in result.items() if row==r) for r in range(2)]==[39,48]
    try:broadcast((2,3),(2,))
    except ValueError:pass
    else:raise AssertionError('an incompatible trailing dimension was accepted')
    assert broadcast((0,3),(1,3))[1]=={}
code/python/vectorized_computation_numpy.py
import numpy as np
if __name__=='__main__':
    a=np.arange(1,7).reshape(2,3);b=np.arange(10,13)
    result=a+b
    np.testing.assert_array_equal(result,[[11,13,15],[14,16,18]])
    np.testing.assert_array_equal(result.sum(axis=1),[39,48])
    np.testing.assert_array_equal(result.sum(axis=0),[25,29,33])
    assert result.sum()==87
    batched=np.arange(1,7).reshape(2,1,3)+np.arange(10,14).reshape(1,4,1)
    assert batched.shape==(2,4,3)
    np.testing.assert_array_equal(batched.sum(axis=-1),[[36,39,42,45],[45,48,51,54]])
    empty=np.empty((0,3),dtype=np.int64)+np.arange(3).reshape(1,3)
    np.testing.assert_array_equal(empty.sum(axis=0),[0,0,0])
    try:a+np.arange(2)
    except ValueError:pass
    else:raise AssertionError('invalid pair broadcasted')
    print('matrix output',result,'batch shape',batched.shape,'empty shape',empty.shape)

Explore: find the correspondence before computing

Compare (2,3)+(3,) with (2,3)+(2,). Predict the output shape or failing trailing axis first. Then inspect the selected source indices for a few elements instead of accepting a diagram by appearance.

Choose scalar broadcast, batched arrays and empty axis. Change the reduction axis, including −1 or all, and verify which axis disappears. Change a starting integer or the elementwise operation and explain which values change without changing shape.

The compatible-but-too-large preset would have shape (4,4,4,4), but the explorer refuses to allocate its 256 output elements. Its valid mathematical broadcasting rule and its resource limit are reported separately. Huge dimensions, invalid syntax and ranks beyond four are rejected at entry.

Common mistakes and counterexamples

Broadcasting aligns trailing dimensions, not the first dimension that happens to have an equal size. A shape-(2,) vector does not automatically mean “one value per row” of a 2×3 matrix; use a size-one trailing dimension when that is the intended operation.

Elementwise multiplication and matrix multiplication use different rules. A reduction removes the selected axis here, while broadcasting can introduce or reuse an axis. Do not call every array a geometric vector or assume vectorization changes the underlying mathematical operation into a dot product.

Numerical considerations

The explorer uses small consecutive integers and exact rational operations, so its shape/value checks are exact. Real numerical libraries may use floating dtypes, different accumulation precisions and different reduction orders; valid shapes do not ensure numerical reliability.

The elementwise operation count equals the number of allocated output elements. Index mapping, memory access, temporary arrays and reduction work add costs. A vectorized expression can reduce interpreter overhead, but this lesson does not infer wall-clock speedups without a meaningful workload measurement.

Engineering and ML connections

Tensor shapes appear in feature matrices, batches, channels, logits, targets and loss reductions. Explicit axes prevent an operation from accidentally combining samples when it should combine features or vocabulary positions. Inspect shapes and representative indices before optimizing a computation; a fast operation on the wrong correspondence is still wrong.

Inspect the corresponding representation and error policy before interpreting a computed value.

Exercises

Predict first, then calculate or test the stated claim. Every answer includes corrective feedback and a worked solution.

calculation

Broadcasted shape

Give the two output dimensions for (2,3)+(3,).

calculation

Index correspondence

A=[[1,2,3],[4,5,6]], B=[10,11,12]. Give C[1,1] for broadcasted A+B.

calculation

Axis reduction

For C=[[11,13,15],[14,16,18]], sum axis one. Give its two output values.

explanation

Incompatible trailing sizes

Why is (2,3)+(2,) incompatible?

Choose one answer

explanation

Vectorization meaning

Which statement about vectorized array computation is correct?

Choose one answer

Summary and checkpoints

Predict a broadcast shape, explain an incompatible trailing axis and map a concrete output element to both source indices. Reproduce the canonical and batched reductions, handle an empty axis, and distinguish mathematical compatibility from the bounded allocation policy and from actual performance.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available