numpy
Arrays, seeded random streams, eigenvalues and least squares with numpy.
linear algebradataDownload (ZIP)Source on GitHub
Preview
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a)
a.sum(axis=0), a.mean(), a[a % 3 == 0], a.T @ a[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]]
(array([12, 15, 18, 21]), np.float64(5.5), array([0, 3, 6, 9]), array([[ 80, 92, 104, 116],
[ 92, 107, 122, 137],
[104, 122, 140, 158],
[116, 137, 158, 179]]))
# Seeded streams match NumPy's exactly
np.random.seed(0)
x = np.random.randn(100_000)
x.mean(), x.std(), np.percentile(x, [5, 50, 95])(np.float64(0.0015767005081253388), np.float64(0.9973396878273816), array([-1.64170792, 0.00172022, 1.644483 ]))
A = np.array([[4.0, 1, 2], [1, 3, 0], [2, 0, 5]])
w, v = np.linalg.eigh(A)
print(w)
np.linalg.solve(A, [1, 2, 3]), np.linalg.det(A), np.allclose(v @ np.diag(w) @ v.T, A)[1.85489731 3.4760236 6.66907909] (array([-0.30232558, 0.76744186, 0.72093023]), np.float64(43.000000000000014), True)
# Least squares and polynomials
x = np.linspace(0, 1, 50)
y = 3 * x**2 - x + 0.05 * np.sin(40 * x)
p = np.polyfit(x, y, 2)
p, np.roots(p)(array([ 3.06605655, -1.06585058, 0.01298164]), array([0.33498999, 0.01263914]))
# A spectrum with the FFT
import matplotlib.pyplot as plt
t = np.linspace(0, 1, 512, endpoint=False)
signal = np.sin(2 * np.pi * 50 * t) + 0.5 * np.sin(2 * np.pi * 120 * t) + 0.3 * np.random.randn(512)
freq = np.fft.rfftfreq(512, d=1 / 512)
plt.figure(figsize=(7, 3)); plt.plot(freq, np.abs(np.fft.rfft(signal))); plt.xlabel('Hz'); plt.title('|FFT|')Files
main.ipynb(8751 bytes)