Skip to content

Examples cookbook

28 runnable examples across arrays, linear algebra, FFT, random, statistics, optimisation and more.

Latest (main)

AI assistant

Build this with Claude Code, Cursor or Copilot

Copy a Tessero-tuned prompt for Examples cookbook, grounded in 16 real API signatures , into your IDE's AI. No chatbot, just exact context.

Each example is a runnable script from the library, shown with its NumPy or SciPy equivalent and the backends it runs on. The FFI package and the native extension run one C kernel and return identical numbers, so every example behaves the same on both. See the user guide for prose, and the API reference for signatures.

Arrays and indexing

Creation And Indexing

ffi ext

Create arrays and read elements/rows. Runs on both backends.

Equivalent: NumPy: np.arange(12).reshape(3, 4); a[1]; np.zeros((2, 3))

Slicing Strides

ffi ext

Strided and negative slicing (NumPy's start:stop:step on a 1-D array). Runs on both backends.

Equivalent: NumPy: v[::2]; v[::-1]; v[-3:]

Graphs (csgraph)

Connected Components

ffi

Connected components of a graph from its adjacency matrix.

Equivalent: SciPy: scipy.sparse.csgraph.connected_components(graph, directed=False) -> (n, labels)

FFT

Dominant Frequency

ffi ext

Find the dominant frequency of a sampled signal with the real FFT. Both backends.

Equivalent: NumPy: F = np.fft.rfft(x); freqs = np.fft.rfftfreq(n, d=1/fs); freqs[np.argmax(np.abs(F))]

Roundtrip

ffi ext

The inverse FFT undoes the forward FFT. Both backends.

Equivalent: NumPy: np.fft.ifft(np.fft.fft(x)).real == x

.npy / .npz and memory maps

Npy Roundtrip

ffi

Save and load arrays in NumPy's .npy and .npz formats (interchangeable with NumPy).

Equivalent: NumPy: np.save / np.load; np.savez / np.load

Laravel bridge

Validation Rule

ffi ext

Validate an incoming numeric array by shape and finiteness with the Laravel rule.

Linear algebra (dense)

Solve And Fit

ffi

Dense linear algebra: solve a square system, and least-squares fit an overdetermined one.

Equivalent: NumPy: np.linalg.solve(A, b); np.linalg.lstsq(A, y, rcond=None)

Math and ufuncs

Out Parameter

ffi ext

Write ufunc results into a preallocated array with the out= parameter (no new allocation).

Equivalent: NumPy: np.sqrt(x, out=buf); np.multiply(x, 2, out=x) (in place)

Ufuncs

ffi ext

Element-wise math (ufuncs), scalar and array broadcasting. Runs on both backends.

Equivalent: NumPy: a + 1; np.sqrt(x); a.prod(); np.add(mat, col) broadcasting (3,) over (2, 3)

Markov decision processes

Value Iteration

ffi

Solve a small Markov decision process with value iteration.

Optimize

Bounded Lbfgsb

ffi

Box-constrained minimisation. Passing `bounds` switches minimize to L-BFGS-B automatically.

Equivalent: SciPy: scipy.optimize.minimize(f, x0, method='L-BFGS-B', bounds=[(-2, 0.5), (None, None)])

Breakeven Brentq

ffi

Bracketed root finding with Brent's method.

Equivalent: SciPy: scipy.optimize.brentq(f, a, b)

Decay Leastsq

ffi

Nonlinear least squares from an explicit residual function (Levenberg-Marquardt).

Equivalent: SciPy: scipy.optimize.leastsq(residuals, p0) / least_squares(residuals, p0)

Demand Curve Fit

ffi

Nonlinear curve fitting.

Equivalent: SciPy: scipy.optimize.curve_fit(model, xdata, ydata, p0) -> (params, covariance)

Implied Yield Newton

ffi

Newton's method for a scalar root (no bracket needed, uses a numerical derivative here).

Equivalent: SciPy: scipy.optimize.newton(f, x0)

Nelder Mead Fmin

ffi

Derivative-free minimisation with the Nelder-Mead simplex via fmin.

Equivalent: SciPy: scipy.optimize.fmin(func, x0) (returns the minimiser)

Rosenbrock Bfgs

ffi

Unconstrained minimisation with quasi-Newton BFGS.

Equivalent: SciPy: scipy.optimize.minimize(rosen, [-1.2, 1.0], method='BFGS')

Random

Monte Carlo

ffi ext

A seeded Monte-Carlo simulation, vectorised. Runs on both backends.

Equivalent: NumPy: g = np.random.default_rng(2024); x = g.uniform(size=n); ((x**2+y**2)<=1).mean()*4

Numpy Seed

ffi ext

Reproduce a NumPy random stream from a seed, and snapshot/restore generator state.

Equivalent: NumPy: g = np.random.default_rng(42); g.integers(0, 100, 5); g.standard_normal(4)

Reductions and statistics

Dataset Statistics

ffi ext

Reductions along axes: per-column and per-row statistics of a small dataset. Both backends.

Equivalent: NumPy: a.sum(); a.mean(axis=0); a.std(axis=0, ddof=1); a.max(axis=1)

Sorting and searching

Leaderboard

ffi ext

Sort, rank, and binary-search a 1-D array. Both backends.

Equivalent: NumPy: np.sort(a) == a.sort-copy; a.argsort(); np.searchsorted(sorted, v)

Sparse matrices

Conjugate Gradient

ffi

Solve a sparse symmetric positive-definite system with conjugate gradient.

Equivalent: SciPy: scipy.sparse.linalg.cg(A, b) -> (x, info) (info == 0 means converged)

scipy.special

Combinatorics

ffi ext

Combinatorics with the gamma family. Both backends.

Equivalent: SciPy: scipy.special.comb(n, k); scipy.special.gammaln(x)

Logistic And Erf

ffi ext

Two workhorse special functions: the logistic sigmoid and the error function. Both backends.

Equivalent: SciPy: scipy.special.expit(x); scipy.special.erf(x)

scipy.stats

Ab Test

ffi ext

A/B test: a two-sample t-test on a per-user metric. Both backends.

Equivalent: SciPy: scipy.stats.ttest_ind(a, b) -> statistic, pvalue

Linear Regression

ffi ext

Ordinary least-squares line fit with correlation and significance. Both backends.

Equivalent: SciPy: scipy.stats.linregress(x, y) -> slope, intercept, rvalue, pvalue, stderr, ...

Normal Distribution

ffi ext

Work with a distribution object: pdf/cdf/ppf of the standard normal. Both backends.

Equivalent: SciPy: scipy.stats.norm(0, 1).cdf(1.96); .ppf(0.975)