Overview
Calculus and solvers. The SciPy-shaped pieces that need derivatives and small dense solves: automatic differentiation, ODE solvers, interpolation and splines, quadrature, root finding and optimisation. FFT and signal processing are the sibling package riptide_numerics_signal; arrays and large/GPU linear algebra are riptide_numerics_cpu (part A).
| Library | Contents |
|---|---|
autodiff.ray | Forward mode (Dual, an extension type over Float64x2: no allocation) and reverse mode (tape) |
ode.ray | RK4, Dormand–Prince RK45, Tsit5 (dense output, events), BDF, Radau IIA, symplectic integrators, batched ensembles |
interpolate.ray | Linear, cubic, B-splines, NURBS, Akima, PCHIP, Catmull–Rom, bicubic/tricubic, RBF |
quadrature.ray | Gauss–Legendre/Kronrod (adaptive), Romberg, tanh-sinh, Monte Carlo / Sobol |
optimize.ray | Bisection, Brent, Newton/Halley, secant; Newton, BFGS, L-BFGS-B, CG, Nelder–Mead, LM, trust region |
linalg.ray | The small dense LU / Cholesky / QR / tridiagonal solves the solvers use (stop-gap for part A) |
Why one package with sub-libraries
The five areas depend on each other: stiff ODE solvers need Jacobians (autodiff) and LU; the optimisers need gradients (autodiff) and Cholesky/QR; spline fitting and RBFs need banded and dense solves; quadrature is used by the spline smoothing penalty. Separate packages would either duplicate the dense kernels or export them as public API of an unrelated package. One package keeps them internal, each area is still its own library (import only ode.ray), and AOT tree shaking drops what an app doesn't call. It is a sibling of riptide_numerics_cpu rather than inside it so part A's core can land and change without touching it; once NDArray lands, the vector-valued APIs here gain NDArray overloads over the same Float64List kernels (an NDArray of float64 is a Float64List plus shape and strides).
Functions and constants
Functions
double derivative(Dual Function(Dual x) f, double x)The derivative f'(x) of a scalar function written over Dual.
import 'raya:math' as math;
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final d = derivative((x) => x.sin() * x, 1.0);
print('d/dx (x sin x) at 1 = ${d.toStringAsFixed(12)}');
print('sin 1 + cos 1 = ${(math.sin(1) + math.cos(1)).toStringAsFixed(12)}');
}d/dx (x sin x) at 1 = 1.381773290676 sin 1 + cos 1 = 1.381773290676
void jacobianForward(DualVectorFunction f, Float64List x, int m, Float64List jac, {Float64List? fx})The m \times n Jacobian of f at x by forward mode (n passes, one seeded direction each), written row-major into jac. fx, when given, receives f(x).
import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Polar to Cartesian: (r, θ) -> (r cos θ, r sin θ). Its Jacobian determinant is r.
final jac = Float64List(4), fx = Float64List(2);
jacobianForward((x, out) {
out[0] = x[0] * x[1].cos();
out[1] = x[0] * x[1].sin();
}, Float64List.fromList([2, math.pi / 6]), 2, jac, fx: fx);
print('f(2, π/6) = [${fx[0].toStringAsFixed(6)}, ${fx[1].toStringAsFixed(6)}]');
print('J = [[${jac[0].toStringAsFixed(6)}, ${jac[1].toStringAsFixed(6)}], [${jac[2].toStringAsFixed(6)}, ${jac[3].toStringAsFixed(6)}]]');
print('det J = ${(jac[0] * jac[3] - jac[1] * jac[2]).toStringAsFixed(10)} (= r)');
}f(2, π/6) = [1.732051, 1.000000] J = [[0.866025, -1.000000], [0.500000, 1.732051]] det J = 2.0000000000 (= r)
void gradientForward(Dual Function(List<Dual> x) f, Float64List x, Float64List grad)The gradient of a scalar function of n variables written over Dual (n forward passes). For large n prefer reverse mode (Tape), which costs one pass.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// f(x, y, z) = xy + yz + zx; gradient (y + z, x + z, x + y).
final g = Float64List(3);
gradientForward((v) => v[0] * v[1] + v[1] * v[2] + v[2] * v[0], Float64List.fromList([1, 2, 3]), g);
print('∇f(1, 2, 3) = $g');
}∇f(1, 2, 3) = [5.0, 4.0, 3.0]
(double, double, double) secondDerivative(HyperDual Function(HyperDual x) f, double x)f(x), f'(x) and f''(x) of a scalar function written over HyperDual, in one evaluation.
import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final (f, d1, d2) = secondDerivative((x) => x.sin() * x.exp(), 0.5);
print('f(0.5) = ${f.toStringAsFixed(10)}');
print("f'(0.5) = ${d1.toStringAsFixed(10)}");
print("f''(0.5) = ${d2.toStringAsFixed(10)} (exact 2eˣcos x = ${(2 * math.exp(0.5) * math.cos(0.5)).toStringAsFixed(10)})");
final xs = [for (var i = 0; i <= 60; i++) -2 + i * 4 / 60];
for (final (k, name) in [(0, 'f'), (1, "f'"), (2, "f''")])
{'label': name, 'points': [for (final x in xs) [x, [secondDerivative((t) => t.sin() * t.exp(), x).$1, secondDerivative((t) => t.sin() * t.exp(), x).$2, secondDerivative((t) => t.sin() * t.exp(), x).$3][k]]]},
]})}');
}f(0.5) = 0.7904390832 f'(0.5) = 2.2373281198 f''(0.5) = 2.8937780732 (exact 2eˣcos x = 2.8937780732)
void hessianForward(HyperDual Function(List<HyperDual> x) f, Float64List x, Float64List hess, {Float64List? grad})The n \times n Hessian of a scalar function written over HyperDual, row-major into hess (\frac{n(n + 1)}{2} evaluations). grad, when given, receives the gradient.
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// f(x, y) = x²y + y³: Hessian [[2y, 2x], [2x, 6y]].
final h = Float64List(4), g = Float64List(2);
hessianForward((v) => v[0].square() * v[1] + v[1].pow(3), Float64List.fromList([1, 2]), h, grad: g);
print('gradient at (1, 2): $g');
print('Hessian: [[${h[0]}, ${h[1]}], [${h[2]}, ${h[3]}]]');
}gradient at (1, 2): [4.0, 13.0] Hessian: [[4.0, 2.0], [2.0, 12.0]]
void hessianVectorProduct(HyperDual Function(List<HyperDual> x) f, Float64List x, Float64List v, Float64List out)The Hessian-vector product \nabla^{2}f(x)·v into out (n evaluations; no Hessian is formed).
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// H·v without building H. f = x²y + y³ at (1, 2) has H = [[4, 2], [2, 12]].
final out = Float64List(2);
hessianVectorProduct((v) => v[0].square() * v[1] + v[1].pow(3), Float64List.fromList([1, 2]),
Float64List.fromList([1, -1]), out);
print('H·(1, −1) = $out (expected [2.0, -10.0])');
}H·(1, −1) = [2.0, -10.0] (expected [2.0, -10.0])
double gradientReverse(VarFunction f, Float64List x, Float64List grad, {Tape? tape})f(x) and its gradient into grad by reverse mode (one forward + one backward pass). Pass a tape to reuse its storage across calls.
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// One backward pass gives every partial derivative. f = Σ sin(xᵢ)·xᵢ.
final x = Float64List.fromList([for (var i = 0; i < 5; i++) i * 0.5]);
final g = Float64List(5);
final f = gradientReverse((v) {
var s = v[0].sin() * v[0];
for (var i = 1; i < v.length; i++) s = s + v[i].sin() * v[i];
return s;
}, x, g);
print('f = ${f.toStringAsFixed(8)}');
for (var i = 0; i < 5; i++) {
print('∂f/∂x$i = ${g[i].toStringAsFixed(8)} (sin + x cos = ${(math.sin(x[i]) + x[i] * math.cos(x[i])).toStringAsFixed(8)})');
}
}f = 4.39602109 ∂f/∂x0 = 0.00000000 (sin + x cos = 0.00000000) ∂f/∂x1 = 0.91821682 (sin + x cos = 0.91821682) ∂f/∂x2 = 1.38177329 (sin + x cos = 1.38177329) ∂f/∂x3 = 1.10360079 (sin + x cos = 1.10360079) ∂f/∂x4 = 0.07700375 (sin + x cos = 0.07700375)
void jacobianReverse(VarVectorFunction f, Float64List x, int m, Float64List jac, {Float64List? fx, Tape? tape})The m \times n Jacobian by reverse mode: one recording, m backward passes (cheaper than forward mode when m < n). Row-major into jac; fx, when given, receives f(x).
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Two outputs of three inputs: f = (xyz, x + y²). Reverse mode costs one backward pass per output row.
final jac = Float64List(6), fx = Float64List(2);
jacobianReverse((v) => [v[0] * v[1] * v[2], v[0] + v[1].square()], Float64List.fromList([1, 2, 3]), 2, jac, fx: fx);
print('f = $fx');
print('row 0: ${jac.sublist(0, 3)}');
print('row 1: ${jac.sublist(3, 6)}');
}f = [6.0, 5.0] row 0: [6.0, 3.0, 2.0] row 1: [1.0, 4.0, 0.0]
void vjp(VarVectorFunction f, Float64List x, Float64List v, Float64List out, {Float64List? fx, Tape? tape})Vector-Jacobian product v^{T} J of f at x into out (length n), one backward pass. Returns f(x) in fx if given.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// vᵀJ in one backward pass, without forming J. f = (x², xy, y²) at (2, 3).
final out = Float64List(2), fx = Float64List(3);
vjp((v) => [v[0].square(), v[0] * v[1], v[1].square()], Float64List.fromList([2, 3]),
Float64List.fromList([1, 1, 1]), out, fx: fx);
print('f = $fx');
print('(1, 1, 1)ᵀ J = $out (expected [7.0, 8.0])');
}f = [4.0, 6.0, 9.0] (1, 1, 1)ᵀ J = [7.0, 8.0] (expected [7.0, 8.0])
int findSpan(Float64List t, int k, double v)The knot span index l with t[l] \le v < t[l + 1] and k \le l < n, where n = t.length - k - 1 (A2.1). Values outside [t[k], t[n]] get the first or last non-empty span, so evaluation extrapolates the end polynomial pieces.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Clamped cubic knots on [0, 4]: 4 repeated ends, interior 1, 2, 3.
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4]);
for (final v in [0.0, 0.5, 2.0, 3.9, 4.0]) {
print('v = $v -> span ${findSpan(t, 3, v)}');
}
}v = 0.0 -> span 3 v = 0.5 -> span 3 v = 2.0 -> span 5 v = 3.9 -> span 6 v = 4.0 -> span 6
void basisFunctions(Float64List t, int k, int l, double v, Float64List out)The k + 1 non-zero basis functions N_{l-k..l, k}(v) into out (A2.2).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Clamped cubic knots on [0, 4]: 4 repeated ends, interior 1, 2, 3.
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4]);
final out = Float64List(4);
basisFunctions(t, 3, findSpan(t, 3, 1.5), 1.5, out);
print('the 4 nonzero basis functions at 1.5: $out (sum ${out.reduce((a, b) => a + b)})');
// All 7 basis functions over [0, 4].
List<List<double>> bi(int j) => [
for (var i = 0; i <= 80; i++)
(() {
final v = 4 * i / 80, l = findSpan(t, 3, v), o = Float64List(4);
basisFunctions(t, 3, l, v, o);
final r = j - (l - 3);
return [v, r >= 0 && r <= 3 ? o[r] : 0.0];
})(),
];
}the 4 nonzero basis functions at 1.5: [0.03125, 0.46875, 0.47916666666666663, 0.020833333333333332] (sum 1.0)
void basisFunctionDerivatives(Float64List t, int k, int l, double v, int nd, Float64List ders)Basis functions and their derivatives up to order nd (A2.3): \operatorname{ders}[d \cdot (k + 1) + r] is the d-th derivative of N_{l-k + r, k} at v.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Clamped cubic knots on [0, 4]: 4 repeated ends, interior 1, 2, 3.
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4]);
final ders = Float64List(3 * 4);
basisFunctionDerivatives(t, 3, findSpan(t, 3, 1.5), 1.5, 2, ders);
print('values: ${ders.sublist(0, 4)}');
print('first: ${ders.sublist(4, 8)}');
print('second: ${ders.sublist(8, 12)}');
print('derivatives of a partition of unity sum to 0: ${ders.sublist(4, 8).reduce((a, b) => a + b).abs() < 1e-12}');
}values: [0.03125, 0.46875, 0.47916666666666663, 0.020833333333333332] first: [-0.1875, -0.5625, 0.625, 0.125] second: [0.75, -0.7499999999999999, -0.5, 0.5] derivatives of a partition of unity sum to 0: true
(Float64List, Float64List) insertKnotRaw(Float64List t, Float64List c, int k, int dim, double u)One Boehm knot insertion on raw arrays: knots t, coefficients c (n x dim), degree k.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 1, 1, 1]);
final c = Float64List.fromList([0, 2, 0]); // a quadratic bump
final (t2, c2) = insertKnotRaw(t, c, 2, 1, 0.5);
print('knots $t2');
print('coefficients $c2');
final a = BSpline(t, c, 2), b = BSpline(t2, c2, 2);
print('same curve: ${(a(0.3) - b(0.3)).abs() < 1e-15}');
}knots [0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0] coefficients [0.0, 1.0, 1.0, 0.0] same curve: true
Float64List notAKnotKnots(Float64List x, int k)SciPy's not-a-knot knot vector for interpolation at x with degree k (Greville-like sites for even k).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2, 3, 4, 5]);
print('cubic: ${notAKnotKnots(x, 3)}');
print('quadratic: ${notAKnotKnots(x, 2)}');
}cubic: [0.0, 0.0, 0.0, 0.0, 2.0, 3.0, 5.0, 5.0, 5.0, 5.0] quadratic: [0.0, 0.0, 0.0, 1.5, 2.5, 3.5, 5.0, 5.0, 5.0]
BSpline makeInterpSpline(Float64List x, Float64List y, {int k = 3, Float64List? t, int dim = 1})The interpolating B-spline of degree k through (x_{i}, y_{i}) (SciPy's make_interp_spline). Knots default to not-a-knot; y may hold dim values per point (row-major) to interpolate curves.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2, 3, 4, 5, 6]);
final y = Float64List.fromList([for (final v in x) math.sin(v)]);
final s = makeInterpSpline(x, y);
print('degree ${s.k}, ${s.n} coefficients');
print('s(2.5) = ${s(2.5).toStringAsFixed(6)}, sin 2.5 = ${math.sin(2.5).toStringAsFixed(6)}');
print('passes through the data: ${[for (var i = 0; i < 7; i++) (s(x[i]) - y[i]).abs() < 1e-12].every((b) => b)}');
}degree 3, 7 coefficients s(2.5) = 0.598744, sin 2.5 = 0.598472 passes through the data: true
BSpline makeLsqSpline(Float64List x, Float64List y, Float64List t, {int k = 3, Float64List? w})The weighted least-squares spline with knots t and degree k (SciPy's make_lsq_spline): minimises \sum (w_{i} (y_{i} - s(x_{i})))^{2} (the weight multiplies the residual, as in SciPy). Solved by Householder QR of the design matrix (the normal equations' solution when the Schoenberg–Whitney conditions hold).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
final x = Float64List.fromList([for (var i = 0; i <= 40; i++) i / 4]);
final y = Float64List.fromList([for (final v in x) math.sin(v) + 0.15 * (rng.nextDouble() - 0.5)]);
final t = Float64List.fromList([0, 0, 0, 0, 2.5, 5, 7.5, 10, 10, 10, 10]);
final s = makeLsqSpline(x, y, t);
print('${s.n} coefficients fit ${x.length} noisy points');
print('s(5) = ${s(5).toStringAsFixed(4)}, sin 5 = ${math.sin(5).toStringAsFixed(4)}');
}7 coefficients fit 41 noisy points s(5) = -0.9967, sin 5 = -0.9589
CubicSpline makeSmoothingSpline(Float64List x, Float64List y, {Float64List? w, double? lam, List<double>? chosenLambda})The cubic smoothing spline minimising \sum w_{i} (y_{i} - f(x_{i}))^{2} + \lambda \int f''(u)^{2} du (SciPy's make_smoothing_spline). lam null chooses \lambda by generalised cross-validation over (0, n] as SciPy does. Reinsch's algorithm: one pentadiagonal solve for the second derivatives \gamma, f(x_{i}) = y_{i} - \lambda w_{i}^{-1} (Q \gamma)_{i}, then the natural cubic spline through those values. chosenLambda, when given, receives \lambda.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(3);
final x = Float64List.fromList([for (var i = 0; i <= 30; i++) i / 5]);
final y = Float64List.fromList([for (final v in x) math.cos(v) + 0.2 * (rng.nextDouble() - 0.5)]);
final chosen = <double>[];
final s = makeSmoothingSpline(x, y, chosenLambda: chosen);
print('λ chosen by generalised cross-validation: ${chosen.first.toStringAsExponential(3)}');
final rough = makeSmoothingSpline(x, y, lam: 1e-6);
}λ chosen by generalised cross-validation: 2.894e-2
int findInterval(Float64List x, double v)Index i of the interval [xi, x[i + 1]) containing v, clamped to [0, x.length - 2].
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2.5, 4]);
for (final v in [-1.0, 0.0, 1.7, 2.5, 9.0]) {
print('v = $v -> interval ${findInterval(x, v)}');
}
}v = -1.0 -> interval 0 v = 0.0 -> interval 0 v = 1.7 -> interval 1 v = 2.5 -> interval 2 v = 9.0 -> interval 2
void solveTridiagonal(Float64List sub, Float64List diag, Float64List sup, Float64List rhs)Solves a tridiagonal system (Thomas algorithm, no pivoting: for diagonally dominant systems such as cubic splines). sub has length n (sub[0] unused), diag n, sup n (\sup[n - 1] unused); rhs is overwritten with x.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// −u'' = 1 on (0, 1) with u(0) = u(1) = 0, 9 interior points: (2, −1) stencil.
const n = 9;
final h = 1 / (n + 1);
final sub = Float64List(n)..fillRange(0, n, -1), diag = Float64List(n)..fillRange(0, n, 2), sup = Float64List(n)..fillRange(0, n, -1);
final rhs = Float64List(n)..fillRange(0, n, h * h);
solveTridiagonal(sub, diag, sup, rhs);
print('u(0.5) = ${rhs[4]} (exact 1/8)');
}u(0.5) = 0.12500000000000003 (exact 1/8)
void matVec(Float64List a, int m, int n, Float64List x, Float64List y)y = A x for a row-major m \times n matrix.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final a = Float64List.fromList([1, 2, 3, 4, 5, 6]); // 2 × 3, row-major
final y = Float64List(2);
matVec(a, 2, 3, Float64List.fromList([1, 0, -1]), y);
print('A x = $y');
}A x = [-2.0, -2.0]
double dot(Float64List a, Float64List b)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print(dot(Float64List.fromList([1, 2, 3]), Float64List.fromList([4, 5, 6])));
}32.0
double norm2(Float64List a)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print(norm2(Float64List.fromList([3, 4])));
print('no overflow: ${norm2(Float64List.fromList([1e200, 1e200]))}');
}5.0 no overflow: 1.414213562373095e+200
double normInf(Float64List a)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print(normInf(Float64List.fromList([3, -7, 4])));
}7.0
double rmsScaled(Float64List x, Float64List scale)RMS norm of x / scale (SciPy's norm(x / scale)).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// The error norm adaptive ODE solvers compare with 1.
final err = Float64List.fromList([1e-4, -2e-4]), scale = Float64List.fromList([1e-3, 1e-3]);
print('rms(err / scale) = ${rmsScaled(err, scale)}');
}rms(err / scale) = 0.15811388300841897
(double, Float64List) validateTolerances(double rtol, Object atol, int n)Tolerances broadcast to n components; rtol is clamped below at 100 \cdot \mathrm{eps} as SciPy does.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final (rtol, atol) = validateTolerances(1e-6, 1e-9, 3);
print('rtol $rtol, atol per component $atol');
final (_, a2) = validateTolerances(1e-6, [1e-3, 1e-6], 2);
print('per-component list: $a2');
final (r3, _) = validateTolerances(1e-20, 1e-9, 1);
print('too small an rtol is raised to $r3');
}rtol 0.000001, atol per component [1e-9, 1e-9, 1e-9] per-component list: [0.001, 0.000001] too small an rtol is raised to 2.220446049250313e-14
double selectInitialStep(OdeFunction f, double t0, Float64List y0, double tBound, double maxStep, Float64List f0, double direction, int order, double rtol, Float64List atol)SciPy's select_initial_step: a first step for a method of order (Hairer I, II.4).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// y' = −y from y(0) = 1: the first step the adaptive solvers would try.
void f(double t, Float64List y, Float64List dy) => dy[0] = -y[0];
final y0 = Float64List.fromList([1]), f0 = Float64List.fromList([-1]);
for (final rtol in [1e-3, 1e-6, 1e-9]) {
final h = selectInitialStep(f, 0, y0, 10, double.infinity, f0, 1, 5, rtol, Float64List.fromList([rtol * 1e-3]));
print('rtol $rtol: h0 = ${h.toStringAsExponential(3)}');
}
}rtol 0.001: h0 = 1.468e-1 rtol 0.000001: h0 = 4.642e-2 rtol 1e-9: h0 = 1.468e-2
double minStepAt(double t, double direction)10 ulps of t in direction: the smallest step the adaptive methods take (SciPy's min_step).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
for (final t in [0.0, 1.0, 1e6]) {
print('t = $t: smallest step ${minStepAt(t, 1).toStringAsExponential(3)}');
}
}t = 0.0: smallest step 4.941e-323 t = 1.0: smallest step 2.220e-15 t = 1000000.0: smallest step 1.164e-9
OdeJacobianFunction odeJacobianFromDual(DualOdeFunction f, int n)A OdeJacobianFunction computed by forward-mode automatic differentiation of f (n passes with Dual numbers).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
// Van der Pol in dual numbers: one definition gives both f and its Jacobian.
void vdp(Dual t, List<Dual> y, List<Dual> dy) {
dy[0] = y[1];
dy[1] = (Dual.constant(1) - y[0].square()) * y[1] * Dual.constant(5) - y[0];
}
void main() {
final jac = odeJacobianFromDual(vdp, 2);
final j = Float64List(4);
jac(0, Float64List.fromList([2, 0]), j);
print('Jacobian at (2, 0): [[${j[0]}, ${j[1]}], [${j[2]}, ${j[3]}]]');
}Jacobian at (2, 0): [[0.0, 1.0], [-1.0, -15.0]]
OdeFunction odeFunctionFromDual(DualOdeFunction f, int n)An OdeFunction that evaluates a DualOdeFunction on plain values (derivative lanes zero).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
// Van der Pol in dual numbers: one definition gives both f and its Jacobian.
void vdp(Dual t, List<Dual> y, List<Dual> dy) {
dy[0] = y[1];
dy[1] = (Dual.constant(1) - y[0].square()) * y[1] * Dual.constant(5) - y[0];
}
void main() {
final f = odeFunctionFromDual(vdp, 2);
final sol = solveIvp(f, (0, 15), [2, 0], method: OdeMethod.radau, jac: odeJacobianFromDual(vdp, 2), rtol: 1e-6);
print('stiff Van der Pol (μ = 5): ${sol.t.length} steps, y(15) = ${sol.y.last[0].toStringAsFixed(4)}');
}stiff Van der Pol (μ = 5): 291 steps, y(15) = 1.4206
Float64List aosToSoa(List<double> aos, int n, int d)Converts n systems of dimension d between row-major [n, d] (the tensor layout) and structure-of-arrays.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 3 particles of dimension 2: (x0, y0, x1, y1, x2, y2) -> (x0, x1, x2, y0, y1, y2).
final aos = [1.0, 10.0, 2.0, 20.0, 3.0, 30.0];
print('SoA: ${aosToSoa(aos, 3, 2)}');
}SoA: [1.0, 2.0, 3.0, 10.0, 20.0, 30.0]
Float64List soaToAos(List<double> soa, int n, int d)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final soa = [1.0, 2.0, 3.0, 10.0, 20.0, 30.0];
print('AoS: ${soaToAos(soa, 3, 2)}');
print('round trip: ${aosToSoa(soaToAos(soa, 3, 2), 3, 2)}');
}AoS: [1.0, 10.0, 2.0, 20.0, 3.0, 30.0] round trip: [1.0, 2.0, 3.0, 10.0, 20.0, 30.0]
TensorGraph rk4EnsembleGraph(String name, int n, int d, double h, int steps, TensorRhs rhs)Records steps fixed RK4 steps of size h for n systems of dimension d: input y0 [n, d] (float32), output y. Run it with CpuInterpreter(graph).run({'y0'...}) or compile it for the GPU (riptide_tensor_gpu). The steps are unrolled, so keep steps moderate (tens) and loop the program for longer runs, feeding y back as y0.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_tensor/riptide_tensor.ray';
void main() {
// Record 20 RK4 steps for 2 oscillators and run the graph on the CPU interpreter.
final g = rk4EnsembleGraph('osc', 2, 2, 0.1, 20, dampedOscillatorRhs(2 * math.pi, 0.1));
final out = CpuInterpreter(g).run({'y0': Float32List.fromList([1, 0, 0.5, 0])})['y']! as Float32List;
print('graph nodes ${g.nodes.length}; y after t = 2: ${out.map((v) => v.toStringAsFixed(4)).toList()}');
}graph nodes 1141; y after t = 2: [0.2813, 0.1438, 0.1407, 0.0719]
TensorRhs dampedOscillatorRhs(double omega, double zeta)Damped harmonic oscillators, d = 2 (x, v): x' = v, v' = -2\zeta\omega v - \omega^{2} x.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_tensor/riptide_tensor.ray';
void main() {
final g = TensorGraph('one');
final y = Tensor.input(g, 'y', [1, 2]);
dampedOscillatorRhs(1, 0.5)(y).output('dy');
final dy = CpuInterpreter(g).run({'y': Float32List.fromList([1, 0])})['dy']! as Float32List;
print('(x, v) = (1, 0) -> (dx, dv) = $dy');
}(x, v) = (1, 0) -> (dx, dv) = [0.0, -1.0]
TensorRhs lorenzRhs({double sigma = 10, double rho = 28, double beta = 8 / 3})The Lorenz system, d = 3.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_tensor/riptide_tensor.ray';
void main() {
final g = TensorGraph('lorenz');
final y = Tensor.input(g, 'y', [1, 3]);
lorenzRhs()(y).output('dy');
final dy = CpuInterpreter(g).run({'y': Float32List.fromList([1, 1, 1])})['dy']! as Float32List;
print('at (1, 1, 1): $dy');
}at (1, 1, 1): [0.0, 26.0, -1.6666667461395264]
TensorRhs centralGravityRhs({double gm = 1, double softening = 1e-3})Particles in a softened central gravity field in the plane, d = 4 (x, y, vx, vy): a = -GM r / (|r|^{2} + \varepsilon^{2})^{1.5}.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_tensor/riptide_tensor.ray';
void main() {
final g = TensorGraph('kepler');
final y = Tensor.input(g, 'y', [1, 4]);
centralGravityRhs()(y).output('dy');
final dy = CpuInterpreter(g).run({'y': Float32List.fromList([2, 0, 0, 0.7])})['dy']! as Float32List;
print('(x, y, vx, vy) = (2, 0, 0, 0.7) -> $dy');
}(x, y, vx, vy) = (2, 0, 0, 0.7) -> [0.0, 0.699999988079071, -0.24999991059303284, 0.0]
OdeFunction dampedOscillatorBatch(int n, double omega, double zeta)The CPU (structure-of-arrays, float64) counterparts of the tensor right-hand sides, for EnsembleIntegrator.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 3 oscillators in one ODE system, structure-of-arrays (x0 x1 x2 v0 v1 v2).
final f = dampedOscillatorBatch(3, 2 * math.pi, 0.1);
final y0 = Float64List.fromList([1, 0.5, -1, 0, 0, 0]);
final sol = solveIvp(f, (0, 3), y0, rtol: 1e-8, denseOutput: true);
print('x(3) = ${[for (var i = 0; i < 3; i++) sol.y.last[i].toStringAsFixed(4)]}');
}x(3) = [0.1497, 0.0749, -0.1497]
OdeFunction lorenzBatch(int n, {double sigma = 10, double rho = 28, double beta = 8 / 3})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final f = lorenzBatch(1);
final sol = solveIvp(f, (0, 25), [1, 1, 1], rtol: 1e-9, atol: 1e-9, denseOutput: true);
print('${sol.t.length} steps; state at t = 25: ${sol.y.last.map((v) => v.toStringAsFixed(3)).toList()}');
}3636 steps; state at t = 25: [-1.493, -2.643, 11.948]
OdeFunction centralGravityBatch(int n, {double gm = 1, double softening = 1e-3})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final f = centralGravityBatch(1, softening: 0);
final sol = solveIvp(f, (0, 10), [1, 0, 0, 1.2], rtol: 1e-10, atol: 1e-12, denseOutput: true);
final p = [for (var i = 0; i <= 200; i++) (() { final s = sol.sol!(i / 20); return [s[0], s[1]]; })()];
print('${sol.t.length} steps; r(10) = ${math.sqrt(sol.y.last[0] * sol.y.last[0] + sol.y.last[1] * sol.y.last[1]).toStringAsFixed(6)}');
}133 steps; r(10) = 2.360960
OdeStepper createStepper(OdeMethod method, OdeFunction f, double t0, Float64List y0, double t1, {double rtol = 1e-3, Object atol = 1e-6, double maxStep = double.infinity, double? firstStep, OdeJacobianFunction? jac})Creates the stepper for method.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) => dy[0] = -2 * t * y[0];
final s = createStepper(OdeMethod.rk45, f, 0, Float64List.fromList([1]), 2, rtol: 1e-8);
final pts = <List<double>>[[0, 1]];
while (s.step()) {
pts.add([s.t, s.y[0]]);
if (s.t >= 2) break;
}
print('${pts.length - 1} steps; y(2) = ${pts.last[1].toStringAsFixed(10)}, exact ${math.exp(-4).toStringAsFixed(10)}');
}16 steps; y(2) = 0.0183159184, exact 0.0183156389
OdeSolution solveIvp(OdeFunction f, (double, double) span, List<double> y0, {OdeMethod method = OdeMethod.rk45, double rtol = 1e-3, Object atol = 1e-6, List<double>? tEval, bool denseOutput = false, List<OdeEvent> events = const [], double maxStep = double.infinity, double? firstStep, OdeJacobianFunction? jac, DualOdeFunction? dualFun})Solves y' = f(t, y), y(t_{0}) = y_{0} on span = (t_{0}, t_{1}), like SciPy's solve_ivp.
jac (stiff methods) is the analytic Jacobian; without it a dualFun gives an automatic one, otherwise finite differences are used. tEval picks the output times (sorted in the integration direction); otherwise every step is returned. events are located on each step's interpolant.
import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// y'' = −y as a system (y, v): y(t) = cos t.
final sol = solveIvp((t, y, dy) {
dy[0] = y[1];
dy[1] = -y[0];
}, (0, 2 * math.pi), Float64List.fromList([1, 0]), rtol: 1e-9, atol: 1e-12, denseOutput: true);
final y = sol.sol!(math.pi);
print('y(π) = ${y[0].toStringAsFixed(8)} (exact −1)');
{'label': 'y', 'points': [for (var i = 0; i <= 40; i++) [i * math.pi / 20, sol.sol!(i * math.pi / 20)[0]]]}
]})}');
}y(π) = -1.00000000 (exact −1)
double brentRoot(double Function(double) f, double a, double b, {double xtol = 2e-12, double rtol = 8.881784197001252e-16, int maxIter = 100})Brent's root finder on [a, b] (f(a) and f(b) of opposite sign or zero), as SciPy's brentq.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = brentRoot((x) => math.cos(x) - x, 0, 1);
print('cos x = x at ${r.toStringAsFixed(15)}');
}cos x = x at 0.739085133215156
ValueAndGradient valueAndGradientForward(Dual Function(List<Dual> x) f)A value-and-gradient callback from a function written over Dual (forward mode: n passes per call).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final fg = valueAndGradientForward((x) => (Dual.constant(1) - x[0]).square() + (x[1] - x[0].square()).square().scale(100));
final g = Float64List(2);
final v = fg(Float64List.fromList([-1, 1]), g);
print('f(−1, 1) = $v, ∇f = $g');
final r = minimizeBfgs(fg, Float64List.fromList([-1.2, 1]));
print('BFGS minimum at ${r.x.map((v) => v.toStringAsFixed(6)).toList()}');
}f(−1, 1) = 4.0, ∇f = [-4.0, 0.0] BFGS minimum at [1.000000, 1.000000]
ValueAndGradient valueAndGradientReverse(VarFunction f)A value-and-gradient callback from a function written over Var (reverse mode: one backward pass per call; the tape is reused across calls).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final fg = valueAndGradientReverse((x) => (x[0] - x[1]).square() + x[0].sin());
final g = Float64List(2);
final v = fg(Float64List.fromList([1, 2]), g);
print('f = ${v.toStringAsFixed(6)}, ∇f = ${g.map((x) => x.toStringAsFixed(6)).toList()}');
}f = 1.841471, ∇f = [-1.459698, 2.000000]
ValueAndGradient valueAndGradientNumeric(ObjectiveFunction f, {double? step})A value-and-gradient callback from a plain objective by central differences (2n extra evaluations per call).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final fg = valueAndGradientNumeric((x) => x[0] * x[0] * x[1] + math.exp(x[1]));
final g = Float64List(2);
fg(Float64List.fromList([1, 0]), g);
print('numeric ∇f = ${g.map((v) => v.toStringAsFixed(7)).toList()} (exact [0, 2])');
}numeric ∇f = [0.0000000, 2.0000000] (exact [0, 2])
JacobianFunction jacobianNumeric(VectorFunction f, int m)A Jacobian callback by forward differences of f (m outputs): n extra evaluations per call.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(Float64List x, Float64List out) {
out[0] = x[0] * x[1];
out[1] = math.sin(x[0]);
}
final jac = jacobianNumeric(f, 2);
final j = Float64List(4);
jac(Float64List.fromList([1, 2]), j);
print('J ≈ ${j.map((v) => v.toStringAsFixed(6)).toList()}');
}J ≈ [2.000000, 1.000000, 0.540302, 0.000000]
JacobianFunction jacobianFromDual(DualVectorFunction f, int m)A Jacobian callback from a vector function written over Dual (forward mode).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final jac = jacobianFromDual((x, out) {
out[0] = x[0] * x[1];
out[1] = x[0].sin();
}, 2);
final j = Float64List(4);
jac(Float64List.fromList([1, 2]), j);
print('exact J = $j');
}exact J = [2.0, 1.0, 0.5403023058681398, 0.0]
OptimizeResult minimizeLbfgsb(ValueAndGradient fg, Float64List x0, {Float64List? lower, Float64List? upper, int m = 10, double ftol = 2.220446049250313e-09, double gtol = 1e-5, int maxiter = 15000, int maxfun = 15000})Minimises f subject to \operatorname{lower}[i] \le x[i] \le \mathrm{upper}[i] (use ±infinity for no bound). lower/upper null means unbounded, so this is also plain L-BFGS.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final fg = valueAndGradientForward((x) => (x[0] - Dual.constant(3)).square() + (x[1] + Dual.constant(1)).square());
final free = minimizeLbfgsb(fg, Float64List.fromList([0, 0]));
final boxed = minimizeLbfgsb(fg, Float64List.fromList([0, 0]), lower: Float64List.fromList([0, 0]), upper: Float64List.fromList([2, 2]));
print('unconstrained: ${free.x}');
print('in [0, 2]²: ${boxed.x} (${boxed.message})');
}unconstrained: [3.0, -1.0] in [0, 2]²: [2.0, 0.0] (converged: projected gradient <= gtol)
OptimizeResult leastSquaresLm(VectorFunction residuals, Float64List x0, int m, {JacobianFunction? jacobian, double ftol = 1e-8, double xtol = 1e-8, double gtol = 1e-8, int? maxfev})Least squares by Levenberg–Marquardt. residuals writes the m residuals; jacobian the m \times n Jacobian (default: forward differences; pass jacobianFromDual for exact derivatives). Defaults follow SciPy's least_squares (ftol = \mathrm{xtol} = \mathrm{gtol} = 1 \times 10^{-8}, max_nfev = 100 n).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Fit y = a·e^(b t) to 8 noisy points.
final rng = math.Random(5);
final t = [for (var i = 0; i < 8; i++) i / 2];
final y = [for (final s in t) 2 * math.exp(-0.7 * s) + 0.02 * (rng.nextDouble() - 0.5)];
void res(Float64List p, Float64List out) {
for (var i = 0; i < 8; i++) {
out[i] = p[0] * math.exp(p[1] * t[i]) - y[i];
}
}
final r = leastSquaresLm(res, Float64List.fromList([1, 0]), 8);
print('a = ${r.x[0].toStringAsFixed(4)}, b = ${r.x[1].toStringAsFixed(4)} after ${r.nit} iterations');
}a = 1.9944, b = -0.6976 after 6 iterations
OptimizeResult leastSquaresDogbox(VectorFunction residuals, Float64List x0, int m, {JacobianFunction? jacobian, Float64List? lower, Float64List? upper, double ftol = 1e-8, double xtol = 1e-8, double gtol = 1e-8, int? maxfev})Bounded least squares by the rectangular trust-region dogleg ('dogbox'). lower/upper may hold ±infinity.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Fit y = a·e^(b t) to 8 noisy points.
final rng = math.Random(5);
final t = [for (var i = 0; i < 8; i++) i / 2];
final y = [for (final s in t) 2 * math.exp(-0.7 * s) + 0.02 * (rng.nextDouble() - 0.5)];
void res(Float64List p, Float64List out) {
for (var i = 0; i < 8; i++) {
out[i] = p[0] * math.exp(p[1] * t[i]) - y[i];
}
}
final r = leastSquaresDogbox(res, Float64List.fromList([1, 0]), 8, lower: Float64List.fromList([0, -0.5]), upper: Float64List.fromList([5, 0]));
print('with b ≥ −0.5: a = ${r.x[0].toStringAsFixed(4)}, b = ${r.x[1].toStringAsFixed(4)}');
}with b ≥ −0.5: a = 1.7596, b = -0.5000
OptimizeResult solveNewton(VectorFunction system, Float64List x0, {JacobianFunction? jacobian, double tol = 1e-10, double xtol = 1e-12, int maxiter = 100})Solves the square system F(x) = 0 by Newton's method with backtracking on \tfrac{1}{2}\Vert F\Vert^{2}. jacobian defaults to forward differences. Converges quadratically near a regular root. fun in the result is \tfrac{1}{2}\Vert F(x)\Vert^{2}.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// x² + y² = 4 and y = x³: two curves meet.
void f(Float64List v, Float64List out) {
out[0] = v[0] * v[0] + v[1] * v[1] - 4;
out[1] = v[1] - v[0] * v[0] * v[0];
}
final r = solveNewton(f, Float64List.fromList([1, 1]));
print('(${r.x[0].toStringAsFixed(8)}, ${r.x[1].toStringAsFixed(8)}) in ${r.nit} iterations');
}(1.17422174, 1.61901306) in 5 iterations
OptimizeResult linprog(Float64List c, {Float64List? aUb, Float64List? bUb, Float64List? aEq, Float64List? bEq, Float64List? lower, Float64List? upper, int maxiter = 10000})Solves the linear program min c^{T}x s.t. aUb x ≤ bUb, aEq x = bEq, lower \le x ≤ upper. Matrices are row-major with x.length = c.length columns. Result fun is c^{T}x; success false with a message on infeasible or unbounded problems.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Maximise x + 2y (minimise −x − 2y) with x + y ≤ 4, x − y ≤ 2, y ≤ 3, x, y ≥ 0.
final r = linprog(Float64List.fromList([-1, -2]),
aUb: Float64List.fromList([1, 1, 1, -1, 0, 1]), bUb: Float64List.fromList([4, 2, 3]));
print('optimum at ${r.x}, value ${-r.fun}');
}optimum at [1.0, 3.0], value 7.0
OptimizeResult quadprog(Float64List g, Float64List c, {Float64List? aEq, Float64List? bEq, Float64List? aUb, Float64List? bUb, Float64List? x0, int maxiter = 1000})Solves the convex QP min \tfrac{1}{2}x^{T}[g]x + cᵀx s.t. aEq x = bEq, aUb x ≤ bUb by the primal active-set method. g is n \times n row-major. x0, when given, must be feasible; otherwise a feasible point is found by the simplex phase 1. Result fun is the objective; grad holds the Lagrange multipliers of the inequality rows (\ge 0).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Minimise x² + y² − 2x − 6y with x + y = 2.
final r = quadprog(Float64List.fromList([2, 0, 0, 2]), Float64List.fromList([-2, -6]),
aEq: Float64List.fromList([1, 1]), bEq: Float64List.fromList([2]));
print('x = ${r.x}, f = ${r.fun}');
}x = [0.0, 2.0], f = -8.0
OptimizeResult minimizeBfgs(ValueAndGradient fg, Float64List x0, {double gtol = 1e-5, int? maxiter})BFGS with a strong-Wolfe line search. Stops when \Vert\nabla f\Vert\infty ≤ gtol.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// The Rosenbrock valley; the gradient comes from forward-mode autodiff.
Dual rosen(List<Dual> v) => (Dual.constant(1) - v[0]).square() + (v[1] - v[0].square()).square().scale(100);
final best = minimizeBfgs(valueAndGradientForward(rosen), Float64List.fromList([-1.2, 1.0]));
print('minimum at (${best.x[0].toStringAsFixed(6)}, ${best.x[1].toStringAsFixed(6)}), exact (1, 1)');
}minimum at (1.000000, 1.000000), exact (1, 1)
OptimizeResult minimizeCg(ValueAndGradient fg, Float64List x0, {double gtol = 1e-5, int? maxiter})Nonlinear conjugate gradient, Polak–Ribière+ with a strong-Wolfe line search (c_{2} = 0.4, SciPy's method='CG').
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final fg = valueAndGradientForward((x) => (Dual.constant(1) - x[0]).square() + (x[1] - x[0].square()).square().scale(100));
final r = minimizeCg(fg, Float64List.fromList([-1.2, 1]));
print('minimum ${r.x.map((v) => v.toStringAsFixed(5)).toList()} in ${r.nit} iterations, ${r.nfev} evaluations');
}minimum [1.00000, 1.00000] in 29 iterations, 121 evaluations
OptimizeResult minimizeNewton(ValueAndGradient fg, HessianFunction hess, Float64List x0, {double gtol = 1e-8, int maxiter = 200})Newton's method with an exact Hessian (e.g. hessianForward over HyperDual): the Newton step from a Cholesky factorisation of \nabla^{2}f + \tau I (\tau raised until positive definite, Nocedal & Wright Alg. 3.3) and a Wolfe line search. Quadratic convergence near a minimum.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final fg = valueAndGradientForward((x) => (Dual.constant(1) - x[0]).square() + (x[1] - x[0].square()).square().scale(100));
void hess(Float64List x, Float64List h) => hessianForward((v) => (HyperDual.constant(1) - v[0]).square() + (v[1] - v[0].square()).square().scale(100), x, h);
final r = minimizeNewton(fg, hess, Float64List.fromList([-1.2, 1]));
print('Newton: ${r.x.map((v) => v.toStringAsFixed(8)).toList()} in ${r.nit} iterations');
}Newton: [1.00000000, 1.00000000] in 22 iterations
OptimizeResult minimizeNelderMead(ObjectiveFunction f, Float64List x0, {double xatol = 1e-4, double fatol = 1e-4, int? maxiter, int? maxfev, bool adaptive = true})Nelder–Mead simplex search (no derivatives), SciPy's method='Nelder-Mead' with adaptive=True parameters.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
double f(Float64List x) => (1 - x[0]) * (1 - x[0]) + 100 * (x[1] - x[0] * x[0]) * (x[1] - x[0] * x[0]);
final r = minimizeNelderMead(f, Float64List.fromList([-1.2, 1]), xatol: 1e-8, fatol: 1e-8);
print('no derivatives: ${r.x.map((v) => v.toStringAsFixed(5)).toList()}, ${r.nfev} evaluations');
}no derivatives: [1.00000, 1.00000], 219 evaluations
ScalarResult bisect(double Function(double x) f, double a, double b, {double xtol = 2e-12, double rtol = 4 * _eps, int maxiter = 200})Bisection on [a, b] (f(a) and f(b) of opposite sign). Linear convergence, always succeeds.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final r = bisect((x) => x * x - 2, 0, 2);
print('√2 by bisection: ${r.x.toStringAsFixed(10)}');
}√2 by bisection: 1.4142135624
ScalarResult brentq(double Function(double x) f, double a, double b, {double xtol = 2e-12, double rtol = 4 * _eps, int maxiter = 100})Brent's method on a bracket [a, b] (SciPy's brentq): inverse quadratic interpolation with bisection safeguards.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Newton's classic example: x³ − 2x − 5 = 0 between 2 and 3.
final r = brentq((x) => x * x * x - 2 * x - 5, 2, 3);
print('root = ${r.x.toStringAsFixed(12)}');
print('f(root) is about 0: ${(r.x * r.x * r.x - 2 * r.x - 5).abs() < 1e-10}');
}root = 2.094551481542 f(root) is about 0: true
ScalarResult newton(double Function(double x) f, double x0, {double Function(double x)? fprime, double Function(double x)? fprime2, double tol = 1.48e-8, int maxiter = 50})Newton's method from x0 (SciPy's newton): with fprime it is Newton (quadratic convergence), with fprime and fprime2 Halley (cubic), with neither the secant method (order 1.618).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = newton((x) => x * x - 2, 1, fprime: (x) => 2 * x);
print('√2 ≈ ${r.x} in ${r.iterations} iterations');
final s = newton((x) => x * x - 2, 1);
print('without a derivative (secant): ${s.x}');
}√2 ≈ 1.4142135623730951 in 5 iterations without a derivative (secant): 1.414213562373095
ScalarResult secant(double Function(double x) f, double x0, {double? x1, double tol = 1.48e-8, int maxiter = 50})The secant method from x0 and x1 (default x_{0} \cdot (1 + 1 \times 10^{-4}) + 1 \times 10^{-4}, SciPy's choice).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = secant((x) => math.exp(x) - 3, 0);
print('ln 3 ≈ ${r.x} (${r.iterations} iterations), ln 3 = ${math.log(3)}');
}ln 3 ≈ 1.0986122886681096 (9 iterations), ln 3 = 1.0986122886681098
ScalarResult newtonAD(Dual Function(Dual x) f, double x0, {double tol = 1.48e-8, int maxiter = 50})Newton's method with the derivative from forward-mode autodiff (one Dual evaluation per iteration).
import 'raya:math' as math;
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Newton's method with the derivative from automatic differentiation.
final r = newtonAD((x) => x * x * x - Dual.constant(2), 1.0);
print('cube root of 2 = ${r.x.toStringAsFixed(12)}');
print('pow(2, 1/3) = ${math.pow(2, 1 / 3).toStringAsFixed(12)}');
}cube root of 2 = 1.259921049895 pow(2, 1/3) = 1.259921049895
ScalarResult halleyAD(HyperDual Function(HyperDual x) f, double x0, {double tol = 1.48e-8, int maxiter = 50})Halley's method with f' and f'' from one HyperDual evaluation per iteration (cubic convergence).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = halleyAD((x) => x * x * x - HyperDual.constant(2), 1);
print('∛2 = ${r.x.toStringAsFixed(15)} in ${r.iterations} iterations (cubic convergence)');
print('Newton needs ${newtonAD((x) => x * x * x - Dual.constant(2), 1.0).iterations}');
}∛2 = 1.259921049894873 in 4 iterations (cubic convergence) Newton needs 5
ScalarResult minimizeScalarBounded(double Function(double x) f, double a, double b, {double xatol = 1e-5, int maxiter = 500})The minimum of f on [a, b] by Brent's method (SciPy's minimize_scalar(method='bounded') / fminbound).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = minimizeScalarBounded((x) => math.sin(x) + math.sin(10 * x / 3), 2.7, 7.5);
print('minimum at x = ${r.x.toStringAsFixed(6)}, f = ${r.fun.toStringAsFixed(6)}');
}minimum at x = 5.145736, f = -1.899599
ScalarResult goldenSection(double Function(double x) f, double a, double b, {double xtol = 1e-8, int maxiter = 500})Golden-section search for the minimum of a unimodal f on [a, b] (linear convergence, no assumptions on smoothness).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = goldenSection((x) => (x - 1.3) * (x - 1.3) + 0.5, 0, 3);
print('x = ${r.x.toStringAsFixed(8)}, evaluations ${r.evaluations}');
}x = 1.30000000, evaluations 40
QuadResult monteCarlo(double Function(Float64List x) f, List<double> lower, List<double> upper, {int n = 100000, math.Random? rng})∫ over [lower, upper] of f by plain Monte Carlo with n uniform points; the error is one standard error.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// The area of the unit disc: integrate the indicator over [−1, 1]².
final r = monteCarlo((x) => x[0] * x[0] + x[1] * x[1] <= 1 ? 1 : 0, [-1, -1], [1, 1], n: 20000, rng: math.Random(42));
print('π ≈ ${r.value.toStringAsFixed(4)} ± ${r.error.toStringAsFixed(4)}');
}π ≈ 3.1456 ± 0.0116
QuadResult quasiMonteCarlo(double Function(Float64List x) f, List<double> lower, List<double> upper, {int n = 4096, int replicates = 8, math.Random? rng})∫ over [lower, upper] of f by randomised quasi-Monte Carlo: replicates digitally shifted Sobol sequences of n points each (n a power of two keeps the balance properties); the value is their mean and the error the standard error across replicates. For smooth integrands the error falls close to O(\frac{1}{n}), against O(\frac{1}{\sqrt{n}}) for Monte Carlo.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = quasiMonteCarlo((x) => x[0] * x[0] + x[1] * x[1] <= 1 ? 1 : 0, [-1, -1], [1, 1], n: 4096, rng: math.Random(42));
final m = monteCarlo((x) => x[0] * x[0] + x[1] * x[1] <= 1 ? 1 : 0, [-1, -1], [1, 1], n: 32768, rng: math.Random(42));
print('Sobol QMC: ${r.value.toStringAsFixed(5)} ± ${r.error.toStringAsFixed(5)}');
print('plain MC: ${m.value.toStringAsFixed(5)} ± ${m.error.toStringAsFixed(5)}');
}Sobol QMC: 3.13721 ± 0.00310 plain MC: 3.14160 ± 0.00907
(double, double, double, double) gaussKronrod21(double Function(double) f, double a, double b)QK21: the 21-point Gauss–Kronrod rule on [a, b] with the 10-point Gauss error estimate.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final (k, g, err, _) = gaussKronrod21((x) => math.exp(-x * x), 0, 2);
print('Kronrod 21: $k');
print('error estimate: ${err.toStringAsExponential(2)}');
}Kronrod 21: 0.8820813907624215 error estimate: 8.82e-1
QuadResult quad(double Function(double) f, double a, double b, {double epsabs = 1.49e-8, double epsrel = 1.49e-8, int limit = 50})\int_{a}^{b} f(x) dx by adaptive Gauss–Kronrod with epsilon-algorithm extrapolation (scipy.integrate.quad). Either bound may be infinite. Stops when error <= max(epsabs, epsrel·|value|) or after limit subintervals.
import 'raya:math' as math;
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final q = quad((x) => math.exp(-x * x), 0, 1);
print('∫₀¹ exp(−x²) dx = ${q.value.toStringAsFixed(12)}');
final s = quad((x) => math.sin(x), 0, math.pi);
print('∫₀^π sin x dx = ${s.value.toStringAsFixed(12)}');
}∫₀¹ exp(−x²) dx = 0.746824132812 ∫₀^π sin x dx = 2.000000000000
(Float64List nodes, Float64List weights) gaussLegendre(int n)Gauss–Legendre nodes and weights on [-1, 1] for n points: exact for polynomials of degree 2n - 1.
import 'raya:math' as math;
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final (nodes, weights) = gaussLegendre(3);
print('3-point nodes: ${[for (final x in nodes) x.toStringAsFixed(6)]}');
print('3-point weights: ${[for (final w in weights) w.toStringAsFixed(6)]}');
// Exact for polynomials up to degree 5: ∫₋₁¹ x⁴ dx = 2/5.
var s = 0.0;
for (var i = 0; i < 3; i++) s += weights[i] * math.pow(nodes[i], 4);
print('∫ x⁴ = ${s.toStringAsFixed(12)}');
}3-point nodes: [-0.774597, 0.000000, 0.774597] 3-point weights: [0.555556, 0.888889, 0.555556] ∫ x⁴ = 0.400000000000
double fixedQuad(double Function(double) f, double a, double b, {int n = 5})\int_{a}^{b} f by n-point Gauss–Legendre (scipy.integrate.fixed_quad).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
for (final n in [2, 3, 5, 8]) {
print('n = $n: ${fixedQuad(math.exp, 0, 1, n: n).toStringAsFixed(14)}');
}
print('exact: ${(math.e - 1).toStringAsFixed(14)}');
}n = 2: 1.71789637800750 n = 3: 1.71828100437252 n = 5: 1.71828182845839 n = 8: 1.71828182845905 exact: 1.71828182845905
QuadResult romberg(double Function(double) f, double a, double b, {double tol = 1.48e-8, double rtol = 1.48e-8, int maxLevels = 20})\int_{a}^{b} f by Romberg integration: trapezoid sums with 2^{k} panels, Richardson-extrapolated, until two diagonal entries agree to tol (absolute) or rtol (relative).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = romberg((x) => 4 / (1 + x * x), 0, 1);
print('∫₀¹ 4/(1 + x²) = ${r.value} (π = ${math.pi}), ${r.evaluations} evaluations');
}∫₀¹ 4/(1 + x²) = 3.1415926536382437 (π = 3.141592653589793), 33 evaluations
QuadResult tanhSinh(double Function(double) f, double a, double b, {double tol = 1e-12, int maxLevel = 10})\int_{a}^{b} f by tanh-sinh (double-exponential) quadrature: x = \tanh(\frac{\pi}{2} \cdot \sinh t), trapezoid in t with step halved each level until successive levels agree to tol·\max(1, |I|). Integrable endpoint singularities (log, power) converge exponentially: nodes approach each endpoint at a double-exponential rate and are computed as distances from the endpoint, so f is never called at the endpoint itself. Finite a < b only.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Endpoint singularities: ∫₀¹ ln x dx = −1.
final r = tanhSinh(math.log, 0, 1);
print('∫₀¹ ln x = ${r.value}, error ${r.error.toStringAsExponential(2)}');
}∫₀¹ ln x = -1.0, error 1.51e-13
QuadResult tanhSinhDistances(double Function(double x, double fromA, double fromB) f, double a, double b, {double tol = 1e-12, int maxLevel = 10})Tanh-sinh with an integrand that also receives each node's distances to the endpoints, f(x, x - a, b - x), computed exactly: write singular factors in terms of them (\frac{1}{\sqrt{1 - x^{2}}} as \frac{1}{\sqrt{(x - a)(b - x)}} on [-1, 1]) and the nodes go all the way to the double-precision underflow, recovering full accuracy that f(x) alone loses to cancellation near the endpoints.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 1/√(x(1 − x)) on (0, 1) = π; the distances to the ends avoid cancellation near 1.
final r = tanhSinhDistances((x, a, b) => 1 / math.sqrt(a * b), 0, 1);
print('${r.value} (π = ${math.pi})');
}3.1415926535897936 (π = 3.141592653589793)
QuadResult quadBox(double Function(Float64List x) f, List<double> lower, List<double> upper, {double epsabs = 1.49e-8, double epsrel = 1.49e-8, int limit = 50})∫ over the box [lower, upper] (any dimension) of f by nested adaptive Gauss–Kronrod (scipy.integrate.nquad): the outermost variable is the first coordinate. Tolerances apply to every level.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = quadBox((x) => math.exp(-(x[0] * x[0] + x[1] * x[1])), [-3, -3], [3, 3]);
print('∬ e^(−x²−y²) over [−3, 3]² = ${r.value.toStringAsFixed(10)} (π·erf(3)² ≈ ${(math.pi * 0.9999779095030014 * 0.9999779095030014).toStringAsFixed(10)})');
}∬ e^(−x²−y²) over [−3, 3]² = 3.1414538564 (π·erf(3)² ≈ 3.1414538564)
Constants and variables
const RkTableau dormandPrince54Dormand–Prince 5(4), as in SciPy's RK45 (the error estimator is 4th order, the solution 5th; dense output is Shampine's 4th-order interpolant).
final RkTableau tsitouras54Tsitouras 5(4) (Tsit5). Its interpolant is the paper's 4th-order free interpolant, expanded to monomials.
Typedefs
typedef DualVectorFunction = void Function(List<Dual> x, List<Dual> out)A vector function written over Dual: reads x (length n), writes out (length m).
typedef VarFunction = Var Function(List<Var> x)A scalar function written over Vars.
typedef VarVectorFunction = List<Var> Function(List<Var> x)A vector function written over Vars: returns its m outputs.
typedef OdeFunction = void Function(double t, Float64List y, Float64List dydt)Dy/dt = f(t, y): reads y, writes dydt. Must not keep references to either list.
typedef OdeJacobianFunction = void Function(double t, Float64List y, Float64List jac)\frac{\partial f}{\partial y} at (t, y), written row-major (n \times n) into jac.
typedef DualOdeFunction = void Function(Dual t, List<Dual> y, List<Dual> dydt)The right-hand side written over Dual numbers, for an automatic Jacobian (see odeJacobianFromDual).
typedef TensorRhs = Tensor Function(Tensor y)A vectorised right-hand side over an [n, d] tensor (autonomous: no t).
typedef AccelerationFunction = void Function(Float64List q, Float64List a)Writes the acceleration a(q) (force / mass) for positions q into a. Both are structure-of-arrays or flat Float64Lists of the same length.
typedef ObjectiveFunction = double Function(Float64List x)An objective f(x).
typedef ValueAndGradient = double Function(Float64List x, Float64List grad)f(x), writing \nabla f(x) into grad.
typedef VectorFunction = void Function(Float64List x, Float64List out)A vector function: reads x, writes out (residuals or a system's equations).
typedef JacobianFunction = void Function(Float64List x, Float64List jac)A Jacobian: reads x, writes the m \times n Jacobian row-major into jac.
typedef HessianFunction = void Function(Float64List x, Float64List hess)A Hessian callback: writes \nabla^{2}f(x) row-major into hess.
Classes
Dual
extension type const Dual._(Float64x2 _p)
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Forward-mode autodiff: x = 3 carries dx = 1, so f(x) = x² + 2x has value 15 and derivative 8.
final x = Dual.variable(3);
final f = x * x + x.scale(2);
print('f(3) = ${f.value}, f\'(3) = ${f.deriv}');
}f(3) = 15.0, f'(3) = 8.0
Constructors
Dual(double value, [double deriv = 0])Value + deriv·\varepsilon.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// A dual number a + bε: here 2 + 3ε. Arithmetic carries the ε part as a derivative.
final a = Dual(2, 3);
print('value ${a.value}, deriv ${a.deriv}');
final b = Dual(5);
print('Dual(5) has deriv ${b.deriv}');
print('(2 + 3ε)(5) = ${(a * b).value} + ${(a * b).deriv}ε');
}value 2.0, deriv 3.0 Dual(5) has deriv 0.0 (2 + 3ε)(5) = 10.0 + 15.0ε
Dual.constant(double value)A constant (derivative 0).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Constants carry derivative 0, so they drop out when differentiating.
final x = Dual.variable(4);
final f = x * x + Dual.constant(7);
print('f(4) = ${f.value}, f\'(4) = ${f.deriv}');
}f(4) = 23.0, f'(4) = 8.0
Dual.variable(double value)The independent variable at value (derivative 1).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// The variable you differentiate with respect to carries derivative 1.
final x = Dual.variable(2);
final f = x * x * x;
print('x³ at 2 = ${f.value}, d/dx = ${f.deriv} (3·2² = 12)');
}x³ at 2 = 8.0, d/dx = 12.0 (3·2² = 12)
Static
static Dual atan2(Dual y, Dual x)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Angle of the point (cos t, sin t) is t, so d/dt atan2 = 1.
final t = Dual.variable(1.0);
final a = Dual.atan2(t.sin(), t.cos());
print('atan2(sin 1, cos 1) = ${a.value.toStringAsFixed(10)}');
print('d/dt = ${a.deriv.toStringAsFixed(10)}');
}atan2(sin 1, cos 1) = 1.0000000000 d/dt = 1.0000000000
static Dual max(Dual a, Dual b)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// max picks the larger value and keeps that branch's derivative.
final x = Dual.variable(3);
final m = Dual.max(x * x, x.scale(4));
print('max(x², 4x) at 3 = ${m.value}, slope ${m.deriv} (from 4x)');
final y = Dual.variable(5);
final n = Dual.max(y * y, y.scale(4));
print('max(x², 4x) at 5 = ${n.value}, slope ${n.deriv} (from x²)');
}max(x², 4x) at 3 = 12.0, slope 4.0 (from 4x) max(x², 4x) at 5 = 25.0, slope 10.0 (from x²)
static Dual min(Dual a, Dual b)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = Dual.variable(1);
final m = Dual.min(x.exp(), x.addScalar(2));
print('min(eˣ, x + 2) at 1 = ${m.value.toStringAsFixed(6)}, slope ${m.deriv.toStringAsFixed(6)}');
final y = Dual.variable(2);
final n = Dual.min(y.exp(), y.addScalar(2));
print('min(eˣ, x + 2) at 2 = ${n.value}, slope ${n.deriv}');
}min(eˣ, x + 2) at 1 = 2.718282, slope 2.718282 min(eˣ, x + 2) at 2 = 4.0, slope 1.0
Properties
double get valuedouble get derivMethods
Dual addScalar(double c)This + c for a plain double.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = Dual.variable(1.5);
final y = x.addScalar(10);
print('x + 10 = ${y.value}, derivative still ${y.deriv}');
}x + 10 = 11.5, derivative still 1.0
Dual scale(double c)This · c for a plain double (both lanes scaled: one instruction).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = Dual.variable(2);
final y = x.square().scale(0.5);
print('½x² at 2 = ${y.value}, derivative ${y.deriv}');
}½x² at 2 = 2.0, derivative 2.0
Dual chain(double fv, double dfv)Applies f with f(value) = fv and f'(value) = dfv: (f(a), f'(a) \cdot a').
import 'raya:math' as math;
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Add your own function: pass f(x) and f'(x); chain multiplies by the inner derivative.
// Here the logistic function σ(x), with σ' = σ(1 − σ), applied to 2x.
Dual sigmoid(Dual u) {
final s = 1 / (1 + math.exp(-u.value));
return u.chain(s, s * (1 - s));
}
final x = Dual.variable(0.25);
final y = sigmoid(x.scale(2));
print('σ(2x) at 0.25 = ${y.value.toStringAsFixed(10)}');
print('d/dx = ${y.deriv.toStringAsFixed(10)}');
}σ(2x) at 0.25 = 0.6224593312 d/dx = 0.4700074244
Dual sin()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.sin();
print('sin x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(math.cos(0.5)).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -math.pi + i * (math.pi - (-math.pi)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).sin().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).sin().deriv]]},
]})}');
}sin x at 0.5 = 0.4794255386 derivative = 0.8775825619 exact = 0.8775825619
Dual cos()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.cos();
print('cos x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(-math.sin(0.5)).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -math.pi + i * (math.pi - (-math.pi)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).cos().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).cos().deriv]]},
]})}');
}cos x at 0.5 = 0.8775825619 derivative = -0.4794255386 exact = -0.4794255386
Dual tan()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.tan();
print('tan x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(1 / (math.cos(0.5) * math.cos(0.5))).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -1.3 + i * (1.3 - (-1.3)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).tan().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).tan().deriv]]},
]})}');
}tan x at 0.5 = 0.5463024898 derivative = 1.2984464104 exact = 1.2984464104
Dual exp()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.exp();
print('exp x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(math.exp(0.5)).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -2 + i * (2 - (-2)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).exp().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).exp().deriv]]},
]})}');
}exp x at 0.5 = 1.6487212707 derivative = 1.6487212707 exact = 1.6487212707
Dual log()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.log();
print('log x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(1 / 0.5).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) 0.1 + i * (3 - (0.1)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).log().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).log().deriv]]},
]})}');
}log x at 0.5 = -0.6931471806 derivative = 2.0000000000 exact = 2.0000000000
Dual sqrt()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.sqrt();
print('sqrt x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(0.5 / math.sqrt(0.5)).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) 0.05 + i * (4 - (0.05)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).sqrt().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).sqrt().deriv]]},
]})}');
}sqrt x at 0.5 = 0.7071067812 derivative = 0.7071067812 exact = 0.7071067812
Dual pow(double k)import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.pow(3);
print('x^3 at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(3 * 0.5 * 0.5).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -2 + i * (2 - (-2)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).pow(3).value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).pow(3).deriv]]},
]})}');
}x^3 at 0.5 = 0.1250000000 derivative = 0.7500000000 exact = 0.7500000000
Dual powDual(Dual o)\mathrm{this}^{o} for a dual exponent: exp(o \cdot \log(this)).
import 'raya:math' as math;
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// xˣ: both base and exponent depend on x. d/dx xˣ = xˣ(ln x + 1).
final x = Dual.variable(2);
final y = x.powDual(x);
print('2² = ${y.value.toStringAsFixed(10)}');
print('d/dx xˣ at 2 = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(4 * (math.log(2) + 1)).toStringAsFixed(10)}');
}2² = 4.0000000000 d/dx xˣ at 2 = 6.7725887222 exact = 6.7725887222
Dual tanh()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.tanh();
print('tanh x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(1 - math.pow((math.exp(1) - 1) / (math.exp(1) + 1), 2)).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -3 + i * (3 - (-3)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).tanh().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).tanh().deriv]]},
]})}');
}tanh x at 0.5 = 0.4621171573 derivative = 0.7864477330 exact = 0.7864477330
Dual atan()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.atan();
print('atan x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(1 / (1 + 0.25)).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -4 + i * (4 - (-4)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).atan().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).atan().deriv]]},
]})}');
}atan x at 0.5 = 0.4636476090 derivative = 0.8000000000 exact = 0.8000000000
Dual asin()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.asin();
print('asin x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(1 / math.sqrt(1 - 0.25)).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -0.99 + i * (0.99 - (-0.99)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).asin().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).asin().deriv]]},
]})}');
}asin x at 0.5 = 0.5235987756 derivative = 1.1547005384 exact = 1.1547005384
Dual acos()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.acos();
print('acos x at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(-1 / math.sqrt(1 - 0.25)).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -0.99 + i * (0.99 - (-0.99)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).acos().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).acos().deriv]]},
]})}');
}acos x at 0.5 = 1.0471975512 derivative = -1.1547005384 exact = -1.1547005384
Dual abs()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final a = Dual.variable(-3).abs();
final b = Dual.variable(2).abs();
print('|x| at −3: value ${a.value}, slope ${a.deriv}');
print('|x| at 2: value ${b.value}, slope ${b.deriv}');
}|x| at −3: value 3.0, slope -1.0 |x| at 2: value 2.0, slope 1.0
Dual square()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = Dual.variable(0.5);
final y = x.square();
print('x^2 at 0.5 = ${y.value.toStringAsFixed(10)}');
print('derivative = ${y.deriv.toStringAsFixed(10)}');
print('exact = ${(2 * 0.5).toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -2 + i * (2 - (-2)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, Dual.variable(t).square().value]]},
{'label': "f'", 'points': [for (final t in pts) [t, Dual.variable(t).square().deriv]]},
]})}');
}x^2 at 0.5 = 0.2500000000 derivative = 1.0000000000 exact = 1.0000000000
Operators
Dual operator +(Dual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// x = 3 is the variable; y = 5 is a constant.
final x = Dual.variable(3);
final y = Dual.constant(5);
final r = x + y;
print('x + y = ${r.value}');
print('d/dx (x + y) = 1: ${r.deriv}');
}x + y = 8.0 d/dx (x + y) = 1: 1.0
Dual operator -(Dual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// x = 3 is the variable; y = 5 is a constant.
final x = Dual.variable(3);
final y = Dual.constant(5);
final r = x - y;
print('x - y = ${r.value}');
print('d/dx (x − y) = 1: ${r.deriv}');
}x - y = -2.0 d/dx (x − y) = 1: 1.0
Dual operator -()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = Dual.variable(2);
final y = -x.square();
print('−x² at 2 = ${y.value}, slope ${y.deriv}');
}−x² at 2 = -4.0, slope -4.0
Dual operator *(Dual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// x = 3 is the variable; y = 5 is a constant.
final x = Dual.variable(3);
final y = Dual.constant(5);
final r = x * y;
print('x * y = ${r.value}');
print('d/dx (x·y) = y = 5: ${r.deriv}');
}x * y = 15.0 d/dx (x·y) = y = 5: 5.0
Dual operator /(Dual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// x = 3 is the variable; y = 5 is a constant.
final x = Dual.variable(3);
final y = Dual.constant(5);
final r = x / y;
print('x / y = ${r.value}');
print('d/dx (x / y) = 1/y = 0.2: ${r.deriv}');
}x / y = 0.6000000000000001 d/dx (x / y) = 1/y = 0.2: 0.2
bool operator <(Dual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Comparisons look only at the value, so branches in your function work as usual.
final a = Dual(2, 100), b = Dual(3, -100), c = Dual(2, 0);
print('(2 + 100ε) < (3 − 100ε): ${a < b}');
print('(2 + 100ε) < (2 + 0ε): ${a < c}');
Dual relu(Dual x) => x < Dual.constant(0) ? Dual.constant(0) : x;
print('relu slope at 1.5: ${relu(Dual.variable(1.5)).deriv}');
}(2 + 100ε) < (3 − 100ε): true (2 + 100ε) < (2 + 0ε): false relu slope at 1.5: 1.0
bool operator >(Dual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Comparisons look only at the value, so branches in your function work as usual.
final a = Dual(2, 100), b = Dual(3, -100), c = Dual(2, 0);
print('(2 + 100ε) > (3 − 100ε): ${a > b}');
print('(2 + 100ε) > (2 + 0ε): ${a > c}');
Dual relu(Dual x) => x > Dual.constant(0) ? x : Dual.constant(0);
print('relu slope at 1.5: ${relu(Dual.variable(1.5)).deriv}');
}(2 + 100ε) > (3 − 100ε): false (2 + 100ε) > (2 + 0ε): false relu slope at 1.5: 1.0
bool operator <=(Dual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Comparisons look only at the value, so branches in your function work as usual.
final a = Dual(2, 100), b = Dual(3, -100), c = Dual(2, 0);
print('(2 + 100ε) <= (3 − 100ε): ${a <= b}');
print('(2 + 100ε) <= (2 + 0ε): ${a <= c}');
Dual relu(Dual x) => x < Dual.constant(0) ? Dual.constant(0) : x;
print('relu slope at 1.5: ${relu(Dual.variable(1.5)).deriv}');
}(2 + 100ε) <= (3 − 100ε): true (2 + 100ε) <= (2 + 0ε): true relu slope at 1.5: 1.0
bool operator >=(Dual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Comparisons look only at the value, so branches in your function work as usual.
final a = Dual(2, 100), b = Dual(3, -100), c = Dual(2, 0);
print('(2 + 100ε) >= (3 − 100ε): ${a >= b}');
print('(2 + 100ε) >= (2 + 0ε): ${a >= c}');
Dual relu(Dual x) => x > Dual.constant(0) ? x : Dual.constant(0);
print('relu slope at 1.5: ${relu(Dual.variable(1.5)).deriv}');
}(2 + 100ε) >= (3 − 100ε): false (2 + 100ε) >= (2 + 0ε): true relu slope at 1.5: 1.0
HyperDual
final class HyperDual
A hyper-dual number: v + d1·\varepsilon_{1} + d2·\varepsilon_{2} + d12·\varepsilon_{1}\varepsilon_{2}.
Constructors
const HyperDual(this.v, [this.d1 = 0, this.d2 = 0, this.d12 = 0])import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// v + d1·ε₁ + d2·ε₂ + d12·ε₁ε₂: the ε₁ε₂ part carries a second derivative.
final h = HyperDual(2, 1, 1, 0);
final f = h * h * h;
print('x³ at 2: value ${f.v}, f\' ${f.d1}, f\' ${f.d2}, f\'\' ${f.d12}');
}x³ at 2: value 8.0, f' 12.0, f' 12.0, f'' 12.0
const HyperDual.constant(double value)A constant.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = HyperDual.variable(1.5);
final f = x.square() + HyperDual.constant(4);
print('x² + 4 at 1.5 = ${f.v}, f\' = ${f.d1}, f\'\' = ${f.d12}');
}x² + 4 at 1.5 = 6.25, f' = 3.0, f'' = 2.0
const HyperDual.variable(double value)The independent variable of a scalar function (both directions seeded): f(x), f'(x), f'(x), f''(x).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = HyperDual.variable(2);
print('variable(2): v ${x.v}, d1 ${x.d1}, d2 ${x.d2}, d12 ${x.d12}');
final f = x.pow(4);
print('x⁴ at 2: f = ${f.v}, f\' = ${f.d1}, f\'\' = ${f.d12} (12·2² = 48)');
}variable(2): v 2.0, d1 1.0, d2 1.0, d12 0.0 x⁴ at 2: f = 16.0, f' = 32.0, f'' = 48.0 (12·2² = 48)
Properties
final double vfinal double d1final double d2final double d12Methods
HyperDual addScalar(double c)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final f = HyperDual.variable(3).square().addScalar(-9);
print('x² − 9 at 3: f = ${f.v}, f\' = ${f.d1}, f\'\' = ${f.d12}');
}x² − 9 at 3: f = 0.0, f' = 6.0, f'' = 2.0
HyperDual scale(double c)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final f = HyperDual.variable(1).exp().scale(3);
print('3eˣ at 1: f = ${f.v.toStringAsFixed(8)}, f\'\' = ${f.d12.toStringAsFixed(8)}');
}3eˣ at 1: f = 8.15484549, f'' = 8.15484549
HyperDual chain(double f0, double f1, double f2)f(this) given f(v) = f0, f'(v) = f1, f''(v) = f2.
import 'raya:math' as math;
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Your own function: pass f, f' and f''. Here the logistic σ with σ' = σ(1−σ), σ'' = σ'(1−2σ).
HyperDual sigmoid(HyperDual u) {
final s = 1 / (1 + math.exp(-u.v));
final s1 = s * (1 - s);
return u.chain(s, s1, s1 * (1 - 2 * s));
}
final y = sigmoid(HyperDual.variable(1));
print('σ(1) = ${y.v.toStringAsFixed(10)}');
print('σ\'(1) = ${y.d1.toStringAsFixed(10)}, σ\'\'(1) = ${y.d12.toStringAsFixed(10)}');
}σ(1) = 0.7310585786 σ'(1) = 0.1966119332, σ''(1) = -0.0908577477
HyperDual reciprocal()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.reciprocal();
print('1/x at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(-1 / (0.5 * 0.5)).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).reciprocal().d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) 0.2 + i * (3 - (0.2)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).reciprocal().v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).reciprocal().d1]]},
]})}');
}1/x at 0.5 = 2.0000000000 derivative = -4.0000000000 exact = -4.0000000000 second derivative at 0.5: 16.0000000000
HyperDual sin()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.sin();
print('sin x at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(math.cos(0.5)).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).sin().d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -math.pi + i * (math.pi - (-math.pi)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).sin().v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).sin().d1]]},
]})}');
}sin x at 0.5 = 0.4794255386 derivative = 0.8775825619 exact = 0.8775825619 second derivative at 0.5: -0.4794255386
HyperDual cos()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.cos();
print('cos x at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(-math.sin(0.5)).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).cos().d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -math.pi + i * (math.pi - (-math.pi)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).cos().v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).cos().d1]]},
]})}');
}cos x at 0.5 = 0.8775825619 derivative = -0.4794255386 exact = -0.4794255386 second derivative at 0.5: -0.8775825619
HyperDual exp()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.exp();
print('exp x at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(math.exp(0.5)).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).exp().d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -2 + i * (2 - (-2)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).exp().v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).exp().d1]]},
]})}');
}exp x at 0.5 = 1.6487212707 derivative = 1.6487212707 exact = 1.6487212707 second derivative at 0.5: 1.6487212707
HyperDual log()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.log();
print('log x at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(1 / 0.5).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).log().d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) 0.1 + i * (3 - (0.1)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).log().v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).log().d1]]},
]})}');
}log x at 0.5 = -0.6931471806 derivative = 2.0000000000 exact = 2.0000000000 second derivative at 0.5: -4.0000000000
HyperDual sqrt()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.sqrt();
print('sqrt x at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(0.5 / math.sqrt(0.5)).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).sqrt().d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) 0.05 + i * (4 - (0.05)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).sqrt().v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).sqrt().d1]]},
]})}');
}sqrt x at 0.5 = 0.7071067812 derivative = 0.7071067812 exact = 0.7071067812 second derivative at 0.5: -0.7071067812
HyperDual pow(double k)import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.pow(3);
print('x^3 at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(3 * 0.5 * 0.5).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).pow(3).d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -2 + i * (2 - (-2)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).pow(3).v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).pow(3).d1]]},
]})}');
}x^3 at 0.5 = 0.1250000000 derivative = 0.7500000000 exact = 0.7500000000 second derivative at 0.5: 3.0000000000
HyperDual tanh()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.tanh();
print('tanh x at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(1 - math.pow((math.exp(1) - 1) / (math.exp(1) + 1), 2)).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).tanh().d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -3 + i * (3 - (-3)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).tanh().v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).tanh().d1]]},
]})}');
}tanh x at 0.5 = 0.4621171573 derivative = 0.7864477330 exact = 0.7864477330 second derivative at 0.5: -0.7268619814
HyperDual atan()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.atan();
print('atan x at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(1 / (1 + 0.25)).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).atan().d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -4 + i * (4 - (-4)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).atan().v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).atan().d1]]},
]})}');
}atan x at 0.5 = 0.4636476090 derivative = 0.8000000000 exact = 0.8000000000 second derivative at 0.5: -0.6400000000
HyperDual square()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final x = HyperDual.variable(0.5);
final y = x.square();
print('x^2 at 0.5 = ${y.v.toStringAsFixed(10)}');
print('derivative = ${y.d1.toStringAsFixed(10)}');
print('exact = ${(2 * 0.5).toStringAsFixed(10)}');
print('second derivative at 0.5: ${HyperDual.variable(0.5).square().d12.toStringAsFixed(10)}');
final pts = [for (var i = 0; i <= 80; i++) -2 + i * (2 - (-2)) / 80];
{'label': 'f', 'points': [for (final t in pts) [t, HyperDual.variable(t).square().v]]},
{'label': "f'", 'points': [for (final t in pts) [t, HyperDual.variable(t).square().d1]]},
]})}');
}x^2 at 0.5 = 0.2500000000 derivative = 1.0000000000 exact = 1.0000000000 second derivative at 0.5: 2.0000000000
Operators
HyperDual operator +(HyperDual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = HyperDual.variable(1.0);
final f = x + x.square();
print('f(1) = ${f.v.toStringAsFixed(10)}');
print("f'(1) = ${f.d1.toStringAsFixed(10)}");
print("f''(1) = ${f.d12.toStringAsFixed(10)}");
}f(1) = 2.0000000000 f'(1) = 3.0000000000 f''(1) = 2.0000000000
HyperDual operator -(HyperDual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = HyperDual.variable(1.0);
final f = x.square() - x;
print('f(1) = ${f.v.toStringAsFixed(10)}');
print("f'(1) = ${f.d1.toStringAsFixed(10)}");
print("f''(1) = ${f.d12.toStringAsFixed(10)}");
}f(1) = 0.0000000000 f'(1) = 1.0000000000 f''(1) = 2.0000000000
HyperDual operator -()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final f = -HyperDual.variable(2).pow(3);
print("−x³ at 2: f = ${f.v}, f' = ${f.d1}, f'' = ${f.d12}");
}−x³ at 2: f = -8.0, f' = -12.0, f'' = -12.0
HyperDual operator *(HyperDual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = HyperDual.variable(1.0);
final f = x * x.sin();
print('f(1) = ${f.v.toStringAsFixed(10)}');
print("f'(1) = ${f.d1.toStringAsFixed(10)}");
print("f''(1) = ${f.d12.toStringAsFixed(10)}");
}f(1) = 0.8414709848 f'(1) = 1.3817732907 f''(1) = 0.2391336269
HyperDual operator /(HyperDual o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final x = HyperDual.variable(1.0);
final f = x.sin() / x;
print('f(1) = ${f.v.toStringAsFixed(10)}');
print("f'(1) = ${f.d1.toStringAsFixed(10)}");
print("f''(1) = ${f.d12.toStringAsFixed(10)}");
}f(1) = 0.8414709848 f'(1) = -0.3011686789 f''(1) = -0.2391336269
Tape
final class Tape
A tape recording operations on Vars for reverse-mode differentiation.
Constructors
Tape([int capacity = 256])import 'raya:math' as math;
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Record z = x·y + sin x, then one backward pass gives ∂z/∂x and ∂z/∂y.
final tape = Tape();
tape.begin();
final x = tape.variable(2), y = tape.variable(3);
final z = x * y + x.sin();
tape.backward(z);
print('z = ${tape.value(z).toStringAsFixed(8)}');
print('∂z/∂x = ${tape.adjoint(x).toStringAsFixed(8)} (y + cos x = ${(3 + math.cos(2)).toStringAsFixed(8)})');
print('∂z/∂y = ${tape.adjoint(y)}');
print('nodes recorded: ${tape.length}');
}z = 6.90929743 ∂z/∂x = 2.58385316 (y + cos x = 2.58385316) ∂z/∂y = 2.0 nodes recorded: 5
Static
static Tape get currentThe tape Var operations record onto (the last one begin was called on).
Properties
Methods
void begin()Clears the recording (keeping the storage) and makes this the active tape.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// begin clears the recording but keeps the storage, so a tape can be reused.
final tape = Tape(16);
for (final x0 in [1.0, 2.0, 3.0]) {
tape.begin();
final x = tape.variable(x0);
final f = x * x * x;
tape.backward(f);
print('x = $x0: f = ${tape.value(f)}, df/dx = ${tape.adjoint(x)}, nodes ${tape.length}');
}
}x = 1.0: f = 1.0, df/dx = 3.0, nodes 3 x = 2.0: f = 8.0, df/dx = 12.0, nodes 3 x = 3.0: f = 27.0, df/dx = 27.0, nodes 3
Var variable(double value)A new independent variable (an input of the function).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final a = tape.variable(1.5);
final b = tape.variable(-2);
final f = a.square() * b;
tape.backward(f);
print('f = a²b = ${tape.value(f)}');
print('∂f/∂a = ${tape.adjoint(a)}, ∂f/∂b = ${tape.adjoint(b)}');
}f = a²b = -4.5 ∂f/∂a = -6.0, ∂f/∂b = 2.25
VarVec variables(Float64List values)A vector of independent variables.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variables(Float64List.fromList([1, 2, 3, 4]));
final f = tape.dot(x, x); // Σ xᵢ²
tape.backward(f);
final g = Float64List(4);
tape.inputAdjoints(g);
print('Σ xᵢ² = ${tape.value(f)}, gradient $g');
}Σ xᵢ² = 30.0, gradient [2.0, 4.0, 6.0, 8.0]
Var constant(double value)A constant (no edges; its adjoint is computed but not used).
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variable(3);
final c = tape.constant(10);
final f = x * c + c;
tape.backward(f);
print('f = 10x + 10 at 3 = ${tape.value(f)}');
print('∂f/∂x = ${tape.adjoint(x)}');
final g = Float64List(1);
tape.inputAdjoints(g);
print('inputs are only the variables: $g');
}f = 10x + 10 at 3 = 40.0 ∂f/∂x = 10.0 inputs are only the variables: [10.0]
double value(Var v)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variable(0.5);
final y = x.exp() * x.cos();
print('tape.value(y) = ${tape.value(y).toStringAsFixed(10)}');
print('y.value = ${y.value.toStringAsFixed(10)}');
}tape.value(y) = 1.4468890366 y.value = 1.4468890366
double adjoint(Var v)The adjoint \frac{\partial out}{\partial v} after backward.
import 'raya:math' as math;
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// After backward, adjoint(v) is ∂out/∂v for every recorded node, inner ones too.
final tape = Tape()..begin();
final x = tape.variable(2);
final u = x.square(); // inner node
final f = u.sin();
tape.backward(f);
print('∂f/∂u = ${tape.adjoint(u).toStringAsFixed(8)} (cos 4)');
print('∂f/∂x = ${tape.adjoint(x).toStringAsFixed(8)} (2x cos x² = ${(4 * math.cos(4)).toStringAsFixed(8)})');
}∂f/∂u = -0.65364362 (cos 4) ∂f/∂x = -2.61457448 (2x cos x² = -2.61457448)
void backward(Var out)Seeds ∂out/∂out = 1 and propagates adjoints to every node.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Gradient of the 2-D Rosenbrock function on a grid of points; one backward pass each.
final tape = Tape();
for (final (x0, y0) in [(-1.0, 1.0), (0.0, 0.0), (1.0, 1.0)]) {
tape.begin();
final x = tape.variable(x0), y = tape.variable(y0);
final f = (tape.constant(1) - x).square() + (y - x.square()).square().scale(100);
tape.backward(f);
print('($x0, $y0): f = ${tape.value(f)}, ∇f = (${tape.adjoint(x)}, ${tape.adjoint(y)})');
}
}(-1.0, 1.0): f = 4.0, ∇f = (-4.0, 0.0) (0.0, 0.0): f = 1.0, ∇f = (-2.0, 0.0) (1.0, 1.0): f = 0.0, ∇f = (0.0, 0.0)
void backwardSeeded(List<Var> outs, Float64List seed)Vector-Jacobian product: seeds the adjoints of outs with seed and propagates; read the result with inputAdjoints. For outputs y = f(x) this gives \mathrm{seed}^{T} \cdot J.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Seeding several outputs gives seedᵀ·J in one pass. Outputs (x + y, x·y) at (2, 5).
final tape = Tape()..begin();
final x = tape.variable(2), y = tape.variable(5);
final outs = [x + y, x * y];
tape.backwardSeeded(outs, Float64List.fromList([1, 0]));
final g = Float64List(2);
tape.inputAdjoints(g);
print('row 0 of J (x + y): $g');
tape.backwardSeeded(outs, Float64List.fromList([0, 1]));
tape.inputAdjoints(g);
print('row 1 of J (x·y): $g');
}row 0 of J (x + y): [1.0, 1.0] row 1 of J (x·y): [5.0, 2.0]
void inputAdjoints(Float64List out)The adjoints of the inputs (in the order they were created) into out.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final v = tape.variables(Float64List.fromList([1, 2, 3]));
final f = v[0] * v[1] * v[2];
tape.backward(f);
final g = Float64List(3);
tape.inputAdjoints(g);
print('∇(xyz) at (1, 2, 3) = $g');
}∇(xyz) at (1, 2, 3) = [6.0, 3.0, 2.0]
VarVec add(VarVec a, VarVec b)Elementwise a + b.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Elementwise a + b, then sum so there is one output to differentiate.
final tape = Tape()..begin();
final a = tape.variables(Float64List.fromList([1, 2, 3]));
final b = tape.variables(Float64List.fromList([10, 20, 30]));
final r = tape.add(a, b);
print('a + b = ${tape.values(r)}');
tape.backward(tape.sum(r));
final g = Float64List(6);
tape.inputAdjoints(g);
print('∂Σ/∂a = ${g.sublist(0, 3)}');
print('∂Σ/∂b = ${g.sublist(3)}');
}a + b = [11.0, 22.0, 33.0] ∂Σ/∂a = [1.0, 1.0, 1.0] ∂Σ/∂b = [1.0, 1.0, 1.0]
VarVec sub(VarVec a, VarVec b)Elementwise a - b.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Elementwise a − b, then sum so there is one output to differentiate.
final tape = Tape()..begin();
final a = tape.variables(Float64List.fromList([1, 2, 3]));
final b = tape.variables(Float64List.fromList([10, 20, 30]));
final r = tape.sub(a, b);
print('a − b = ${tape.values(r)}');
tape.backward(tape.sum(r));
final g = Float64List(6);
tape.inputAdjoints(g);
print('∂Σ/∂a = ${g.sublist(0, 3)}');
print('∂Σ/∂b = ${g.sublist(3)}');
}a − b = [-9.0, -18.0, -27.0] ∂Σ/∂a = [1.0, 1.0, 1.0] ∂Σ/∂b = [-1.0, -1.0, -1.0]
VarVec mul(VarVec a, VarVec b)Elementwise a \cdot b.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Elementwise a · b, then sum so there is one output to differentiate.
final tape = Tape()..begin();
final a = tape.variables(Float64List.fromList([1, 2, 3]));
final b = tape.variables(Float64List.fromList([10, 20, 30]));
final r = tape.mul(a, b);
print('a · b = ${tape.values(r)}');
tape.backward(tape.sum(r));
final g = Float64List(6);
tape.inputAdjoints(g);
print('∂Σ/∂a = ${g.sublist(0, 3)}');
print('∂Σ/∂b = ${g.sublist(3)}');
}a · b = [10.0, 40.0, 90.0] ∂Σ/∂a = [10.0, 20.0, 30.0] ∂Σ/∂b = [1.0, 2.0, 3.0]
VarVec scale(VarVec a, double c)a \cdot c for a constant c.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final v = tape.variables(Float64List.fromList([1, 2, 3]));
final s = tape.scale(v, 2.5);
print('2.5·v = ${tape.values(s)}');
tape.backward(tape.sum(s));
final g = Float64List(3);
tape.inputAdjoints(g);
print('gradient of Σ 2.5vᵢ = $g');
}2.5·v = [2.5, 5.0, 7.5] gradient of Σ 2.5vᵢ = [2.5, 2.5, 2.5]
VarVec sin(VarVec a)import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Elementwise sin on a vector; the adjoints of Σ sin(xᵢ) are the pointwise derivatives.
final xs = Float64List.fromList([for (var i = 0; i <= 40; i++) 0.1 + i * 0.075]);
final tape = Tape(512)..begin();
final v = tape.variables(xs);
final y = tape.sin(v);
tape.backward(tape.sum(y));
final g = Float64List(xs.length);
tape.inputAdjoints(g);
final ys = tape.values(y);
final x = xs[10];
print('sin(${x.toStringAsFixed(2)}) = ${ys[10].toStringAsFixed(8)}, adjoint ${g[10].toStringAsFixed(8)}, exact ${(math.cos(x)).toStringAsFixed(8)}');
{'label': 'sin(x)', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], ys[i]]]},
{'label': 'adjoint', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], g[i]]]},
]})}');
}sin(0.85) = 0.75128041, adjoint 0.65998315, exact 0.65998315
VarVec cos(VarVec a)import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Elementwise cos on a vector; the adjoints of Σ cos(xᵢ) are the pointwise derivatives.
final xs = Float64List.fromList([for (var i = 0; i <= 40; i++) 0.1 + i * 0.075]);
final tape = Tape(512)..begin();
final v = tape.variables(xs);
final y = tape.cos(v);
tape.backward(tape.sum(y));
final g = Float64List(xs.length);
tape.inputAdjoints(g);
final ys = tape.values(y);
final x = xs[10];
print('cos(${x.toStringAsFixed(2)}) = ${ys[10].toStringAsFixed(8)}, adjoint ${g[10].toStringAsFixed(8)}, exact ${(-math.sin(x)).toStringAsFixed(8)}');
{'label': 'cos(x)', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], ys[i]]]},
{'label': 'adjoint', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], g[i]]]},
]})}');
}cos(0.85) = 0.65998315, adjoint -0.75128041, exact -0.75128041
VarVec exp(VarVec a)import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Elementwise exp on a vector; the adjoints of Σ exp(xᵢ) are the pointwise derivatives.
final xs = Float64List.fromList([for (var i = 0; i <= 40; i++) 0.1 + i * 0.075]);
final tape = Tape(512)..begin();
final v = tape.variables(xs);
final y = tape.exp(v);
tape.backward(tape.sum(y));
final g = Float64List(xs.length);
tape.inputAdjoints(g);
final ys = tape.values(y);
final x = xs[10];
print('exp(${x.toStringAsFixed(2)}) = ${ys[10].toStringAsFixed(8)}, adjoint ${g[10].toStringAsFixed(8)}, exact ${(math.exp(x)).toStringAsFixed(8)}');
{'label': 'exp(x)', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], ys[i]]]},
{'label': 'adjoint', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], g[i]]]},
]})}');
}exp(0.85) = 2.33964685, adjoint 2.33964685, exact 2.33964685
VarVec log(VarVec a)import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Elementwise log on a vector; the adjoints of Σ log(xᵢ) are the pointwise derivatives.
final xs = Float64List.fromList([for (var i = 0; i <= 40; i++) 0.1 + i * 0.075]);
final tape = Tape(512)..begin();
final v = tape.variables(xs);
final y = tape.log(v);
tape.backward(tape.sum(y));
final g = Float64List(xs.length);
tape.inputAdjoints(g);
final ys = tape.values(y);
final x = xs[10];
print('log(${x.toStringAsFixed(2)}) = ${ys[10].toStringAsFixed(8)}, adjoint ${g[10].toStringAsFixed(8)}, exact ${(1 / x).toStringAsFixed(8)}');
{'label': 'log(x)', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], ys[i]]]},
{'label': 'adjoint', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], g[i]]]},
]})}');
}log(0.85) = -0.16251893, adjoint 1.17647059, exact 1.17647059
VarVec tanh(VarVec a)import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Elementwise tanh on a vector; the adjoints of Σ tanh(xᵢ) are the pointwise derivatives.
final xs = Float64List.fromList([for (var i = 0; i <= 40; i++) 0.1 + i * 0.075]);
final tape = Tape(512)..begin();
final v = tape.variables(xs);
final y = tape.tanh(v);
tape.backward(tape.sum(y));
final g = Float64List(xs.length);
tape.inputAdjoints(g);
final ys = tape.values(y);
final x = xs[10];
print('tanh(${x.toStringAsFixed(2)}) = ${ys[10].toStringAsFixed(8)}, adjoint ${g[10].toStringAsFixed(8)}, exact ${(1 - math.pow((math.exp(2 * x) - 1) / (math.exp(2 * x) + 1), 2)).toStringAsFixed(8)}');
{'label': 'tanh(x)', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], ys[i]]]},
{'label': 'adjoint', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], g[i]]]},
]})}');
}tanh(0.85) = 0.69106947, adjoint 0.52242299, exact 0.52242299
VarVec square(VarVec a)import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Elementwise square on a vector; the adjoints of Σ square(xᵢ) are the pointwise derivatives.
final xs = Float64List.fromList([for (var i = 0; i <= 40; i++) 0.1 + i * 0.075]);
final tape = Tape(512)..begin();
final v = tape.variables(xs);
final y = tape.square(v);
tape.backward(tape.sum(y));
final g = Float64List(xs.length);
tape.inputAdjoints(g);
final ys = tape.values(y);
final x = xs[10];
print('square(${x.toStringAsFixed(2)}) = ${ys[10].toStringAsFixed(8)}, adjoint ${g[10].toStringAsFixed(8)}, exact ${(2 * x).toStringAsFixed(8)}');
{'label': 'square(x)', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], ys[i]]]},
{'label': 'adjoint', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], g[i]]]},
]})}');
}square(0.85) = 0.72250000, adjoint 1.70000000, exact 1.70000000
Var sum(VarVec a)\sum a_{i} (one node, n edges).
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Mean squared value of a vector and its gradient 2xᵢ/n.
final tape = Tape()..begin();
final v = tape.variables(Float64List.fromList([1, -2, 3, -4]));
final m = tape.sum(tape.square(v)).scale(1 / 4);
tape.backward(m);
final g = Float64List(4);
tape.inputAdjoints(g);
print('mean of squares = ${tape.value(m)}');
print('gradient = $g');
}mean of squares = 7.5 gradient = [0.5, -1.0, 1.5, -2.0]
Var dot(VarVec a, VarVec b)\sum a_{i}b_{i} (one node, 2n edges).
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final a = tape.variables(Float64List.fromList([1, 2, 3]));
final b = tape.variables(Float64List.fromList([4, 5, 6]));
final d = tape.dot(a, b);
tape.backward(d);
final g = Float64List(6);
tape.inputAdjoints(g);
print('a·b = ${tape.value(d)}');
print('∂/∂a = ${g.sublist(0, 3)} (= b), ∂/∂b = ${g.sublist(3)} (= a)');
}a·b = 32.0 ∂/∂a = [4.0, 5.0, 6.0] (= b), ∂/∂b = [1.0, 2.0, 3.0] (= a)
VarVec matVec(Float64List a, int m, VarVec x)y = A x for a constant row-major m \times n matrix a (one node per row, n edges each).
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
// Least-squares loss ‖Ax − b‖² and its gradient 2Aᵀ(Ax − b), by reverse mode.
final a = Float64List.fromList([1, 2, 3, 4, 5, 6]); // 3 x 2
final b = [1.0, 2.0, 2.0];
final tape = Tape()..begin();
final x = tape.variables(Float64List.fromList([0.5, -0.25]));
final ax = tape.matVec(a, 3, x);
var loss = tape.constant(0);
for (var i = 0; i < 3; i++) loss = loss + ax[i].addScalar(-b[i]).square();
tape.backward(loss);
final g = Float64List(2);
tape.inputAdjoints(g);
print('Ax = ${tape.values(ax)}');
print('loss = ${tape.value(loss)}, gradient = $g');
}Ax = [0.0, 0.5, 1.0] loss = 4.25, gradient = [-21.0, -28.0]
Float64List values(VarVec v)The values of v into a new list.
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final v = tape.variables(Float64List.fromList([0, 1, 2]));
print('exp(v) = ${tape.values(tape.exp(v))}');
}exp(v) = [1.0, 2.718281828459045, 7.38905609893065]
Var
extension type const Var._(int _i)
A recorded scalar on the Tape.current tape (an index into it; nothing is allocated).
Static
static Var atan2(Var y, Var x)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final y = tape.variable(1), x = tape.variable(1);
final a = Var.atan2(y, x);
tape.backward(a);
print('atan2(1, 1) = ${a.value.toStringAsFixed(10)} (π/4)');
print('∂/∂y = ${tape.adjoint(y)}, ∂/∂x = ${tape.adjoint(x)}');
}atan2(1, 1) = 0.7853981634 (π/4) ∂/∂y = 0.5, ∂/∂x = -0.5
Properties
double get valueMethods
Var addScalar(double c)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variable(2);
final f = x.square().addScalar(-4);
tape.backward(f);
print('x² − 4 at 2 = ${f.value}, slope ${tape.adjoint(x)}');
}x² − 4 at 2 = 0.0, slope 4.0
Var scale(double c)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variable(3);
final f = x.scale(-0.5);
tape.backward(f);
print('−x/2 at 3 = ${f.value}, slope ${tape.adjoint(x)}');
}−x/2 at 3 = -1.5, slope -0.5
Var sin()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.sin();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('sin at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(math.cos(0.5)).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) -3 + i * (3 - (-3)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}sin at 0.5 = 0.4794255386, slope 0.8775825619, exact slope 0.8775825619
Var cos()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.cos();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('cos at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(-math.sin(0.5)).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) -3 + i * (3 - (-3)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}cos at 0.5 = 0.8775825619, slope -0.4794255386, exact slope -0.4794255386
Var tan()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.tan();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('tan at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(1 / (math.cos(0.5) * math.cos(0.5))).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) -1.3 + i * (1.3 - (-1.3)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}tan at 0.5 = 0.5463024898, slope 1.2984464104, exact slope 1.2984464104
Var exp()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.exp();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('exp at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(math.exp(0.5)).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) -2 + i * (2 - (-2)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}exp at 0.5 = 1.6487212707, slope 1.6487212707, exact slope 1.6487212707
Var log()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.log();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('log at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(2.0).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) 0.1 + i * (3 - (0.1)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}log at 0.5 = -0.6931471806, slope 2.0000000000, exact slope 2.0000000000
Var sqrt()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.sqrt();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('sqrt at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(0.5 / math.sqrt(0.5)).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) 0.05 + i * (4 - (0.05)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}sqrt at 0.5 = 0.7071067812, slope 0.7071067812, exact slope 0.7071067812
Var pow(double k)import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.pow(2.5);
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('pow(2.5) at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(2.5 * math.pow(0.5, 1.5)).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) 0.01 + i * (2 - (0.01)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}pow(2.5) at 0.5 = 0.1767766953, slope 0.8838834765, exact slope 0.8838834765
Var tanh()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.tanh();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('tanh at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(1 - math.pow((math.exp(1) - 1) / (math.exp(1) + 1), 2)).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) -3 + i * (3 - (-3)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}tanh at 0.5 = 0.4621171573, slope 0.7864477330, exact slope 0.7864477330
Var atan()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.atan();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('atan at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(0.8).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) -4 + i * (4 - (-4)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}atan at 0.5 = 0.4636476090, slope 0.8000000000, exact slope 0.8000000000
Var abs()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.abs();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('abs at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(1.0).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) -2 + i * (2 - (-2)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}abs at 0.5 = 0.5000000000, slope 1.0000000000, exact slope 1.0000000000
Var square()import 'raya:math' as math;
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
// Reverse mode on one variable: value and slope, then the whole curve.
final tape = Tape();
(double, double) at(double x0) {
tape.begin();
final x = tape.variable(x0);
final y = x.square();
tape.backward(y);
return (y.value, tape.adjoint(x));
}
final (v, d) = at(0.5);
print('square at 0.5 = ${v.toStringAsFixed(10)}, slope ${d.toStringAsFixed(10)}, exact slope ${(1.0).toStringAsFixed(10)}');
final xs = [for (var i = 0; i <= 60; i++) -2 + i * (2 - (-2)) / 60];
{'label': 'f', 'points': [for (final x in xs) [x, at(x).$1]]},
{'label': 'slope', 'points': [for (final x in xs) [x, at(x).$2]]},
]})}');
}square at 0.5 = 0.2500000000, slope 1.0000000000, exact slope 1.0000000000
Operators
Var operator +(Var o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variable(2), y = tape.variable(5);
final f = x + y;
tape.backward(f);
print('x + y = ${f.value}');
print('∂f/∂x = ${tape.adjoint(x)} (1), ∂f/∂y = ${tape.adjoint(y)} (1)');
}x + y = 7.0 ∂f/∂x = 1.0 (1), ∂f/∂y = 1.0 (1)
Var operator -(Var o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variable(2), y = tape.variable(5);
final f = x - y;
tape.backward(f);
print('x - y = ${f.value}');
print('∂f/∂x = ${tape.adjoint(x)} (1), ∂f/∂y = ${tape.adjoint(y)} (−1)');
}x - y = -3.0 ∂f/∂x = 1.0 (1), ∂f/∂y = -1.0 (−1)
Var operator *(Var o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variable(2), y = tape.variable(5);
final f = x * y;
tape.backward(f);
print('x * y = ${f.value}');
print('∂f/∂x = ${tape.adjoint(x)} (y = 5), ∂f/∂y = ${tape.adjoint(y)} (x = 2)');
}x * y = 10.0 ∂f/∂x = 5.0 (y = 5), ∂f/∂y = 2.0 (x = 2)
Var operator /(Var o)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variable(2), y = tape.variable(5);
final f = x / y;
tape.backward(f);
print('x / y = ${f.value}');
print('∂f/∂x = ${tape.adjoint(x)} (1/y = 0.2), ∂f/∂y = ${tape.adjoint(y)} (−x/y² = −0.08)');
}x / y = 0.4 ∂f/∂x = 0.2 (1/y = 0.2), ∂f/∂y = -0.08000000000000002 (−x/y² = −0.08)
Var operator -()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final x = tape.variable(4);
final f = -x.sqrt();
tape.backward(f);
print('−√x at 4 = ${f.value}, slope ${tape.adjoint(x)}');
}−√x at 4 = -2.0, slope -0.25
VarVec
final class VarVec
A contiguous run of recorded scalars (the reverse-mode view of a float64 vector).
Properties
final int startfinal int lengthOperators
Var operator [](int k)import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
void main() {
final tape = Tape()..begin();
final v = tape.variables(Float64List.fromList([3, 4]));
final r = (v[0].square() + v[1].square()).sqrt();
tape.backward(r);
print('‖(3, 4)‖ = ${r.value}');
print('∂/∂v[0] = ${tape.adjoint(v[0])}, ∂/∂v[1] = ${tape.adjoint(v[1])}');
}‖(3, 4)‖ = 5.0 ∂/∂v[0] = 0.6000000000000001, ∂/∂v[1] = 0.8
BSpline
class BSpline
A spline of degree k in B-spline form: s(v) = \sum c_{i} B_{i, k}(v), knots t (non-decreasing), n = t.length - k - 1 coefficients, each of dimension dim (\dim > 1 for curves; c is n x dim row-major). Evaluation outside [t[k], t[n]] continues the end pieces (SciPy's extrapolate=True).
Constructors
BSpline(this.t, this.c, this.k, {this.dim = 1})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 3, 3, 3]);
final c = Float64List.fromList([0, 1, 3, -1, 2, 0]);
final s = BSpline(t, c, 3);
print('degree ${s.k}, ${s.n} control values, domain [${t[3]}, ${t[6]}]');
print('s(1.5) = ${s(1.5)}');
// A 2-D curve: dim 2, coefficients interleaved (x, y).
final curve = BSpline(Float64List.fromList([0, 0, 0, 1, 2, 2, 2]), Float64List.fromList([0, 0, 1, 2, 3, 0, 4, 2]), 2, dim: 2);
final pts = [for (var i = 0; i <= 40; i++) (() { final o = Float64List(2); curve.evalInto(2 * i / 40, o); return o.toList(); })()];
}degree 3, 6 control values, domain [0.0, 3.0] s(1.5) = 1.03125
Static
static Float64List designMatrix(Float64List x, Float64List t, int k)The m \times n design matrix B_{j}(x_{i}), dense row-major (SciPy's BSpline.design_matrix, as a dense array).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 1, 2, 2, 2]);
final x = Float64List.fromList([0, 0.5, 1, 1.5, 2]);
final a = BSpline.designMatrix(x, t, 2);
final n = t.length - 3;
final rows = [for (var i = 0; i < x.length; i++) [for (var j = 0; j < n; j++) a[i * n + j]]];
for (final r in rows) {
print(r);
}
}[1.0, 0.0, 0.0, 0.0] [0.25, 0.625, 0.125, 0.0] [0.0, 0.5, 0.5, 0.0] [0.0, 0.125, 0.625, 0.25] [0.0, 0.0, 0.0, 1.0]
Properties
final Float64List tfinal Float64List cfinal int kfinal int dimdouble get upperMethods
double call(double v, [int nu = 0])The value (or nuth derivative) of a scalar spline at v.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 3, 3, 3]);
final c = Float64List.fromList([0, 1, 3, -1, 2, 0]);
final s = BSpline(t, c, 3);
print('s(1) = ${s(1)}');
print('s\'(1) = ${s(1, 1)}');
print('s\'\'(1) = ${s(1, 2)}');
}s(1) = 1.833333333333333 s'(1) = -0.5 s''(1) = -7.0
void evalInto(double v, Float64List out, [int nu = 0])The value (or nuth derivative) at v written into out (length dim).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final circleish = BSpline(Float64List.fromList([0, 0, 0, 1, 2, 3, 3, 3]), Float64List.fromList([1, 0, 1, 1, -1, 1, -1, -1, 1, -1]), 2, dim: 2);
final out = Float64List(2);
circleish.evalInto(1.5, out);
print('point at 1.5: $out');
circleish.evalInto(1.5, out, 1);
print('tangent at 1.5: $out');
}point at 1.5: [-0.75, 0.75] tangent at 1.5: [-1.0, -1.0]
Float64List evalAll(Float64List v, [int nu = 0])Evaluates a scalar spline at every point of v.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 3, 3, 3]);
final c = Float64List.fromList([0, 1, 3, -1, 2, 0]);
final s = BSpline(t, c, 3);
final xs = Float64List.fromList([0, 0.5, 1, 1.5, 2, 2.5, 3]);
print(s.evalAll(xs));
print('derivative: ${s.evalAll(xs, 1)}');
}[0.0, 1.3541666666666667, 1.833333333333333, 1.03125, 0.41666666666666674, 0.9895833333333334, 0.0] derivative: [3.0, 2.125, -0.5, -2.0625, 0.25, 0.8125, -6.0]
BSpline derivative([int nu = 1])The derivative spline (degree k - 1, knots t[1..-1]).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 3, 3, 3]);
final c = Float64List.fromList([0, 1, 3, -1, 2, 0]);
final s = BSpline(t, c, 3);
final d = s.derivative();
print('derivative has degree ${d.k}');
print('d(1.2) = ${d(1.2)}, s(1.2, 1) = ${s(1.2, 1)}');
}derivative has degree 2 d(1.2) = -1.5899999999999996, s(1.2, 1) = -1.5899999999999994
BSpline antiderivative()The antiderivative spline (degree k + 1), zero at t[0] (SciPy's splantider: one knot added at each end).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 3, 3, 3]);
final c = Float64List.fromList([0, 1, 3, -1, 2, 0]);
final s = BSpline(t, c, 3);
final a = s.antiderivative();
print('antiderivative degree ${a.k}, a(0) = ${a(0)}');
print('a\'(2) = ${a(2, 1)}, s(2) = ${s(2)}');
}antiderivative degree 4, a(0) = 0.0 a'(2) = 0.41666666666666674, s(2) = 0.41666666666666674
double integrate(double a, double b)\int_{a}^{b} s for a scalar spline.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 3, 3, 3]);
final c = Float64List.fromList([0, 1, 3, -1, 2, 0]);
final s = BSpline(t, c, 3);
print('∫₀³ s = ${s.integrate(0, 3)}');
print('∫₁² s = ${s.integrate(1, 2)}');
print('quad check: ${quad((x) => s(x), 0, 3).value}');
}∫₀³ s = 3.0 ∫₁² s = 1.0624999999999998 quad check: 2.9999999999999996
BSpline insertKnot(double u, [int times = 1])A new spline equal to this one with knot u inserted times times (Boehm's algorithm).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 3, 3, 3]);
final c = Float64List.fromList([0, 1, 3, -1, 2, 0]);
final s = BSpline(t, c, 3);
final r = s.insertKnot(1.5, 2);
print('${s.n} -> ${r.n} coefficients, knots ${r.t}');
print('same values: ${[for (var i = 0; i <= 30; i++) (s(i / 10) - r(i / 10)).abs() < 1e-12].every((b) => b)}');
}6 -> 8 coefficients, knots [0.0, 0.0, 0.0, 0.0, 1.0, 1.5, 1.5, 2.0, 3.0, 3.0, 3.0, 3.0] same values: true
PPoly toPPoly()Converts to piecewise polynomial form over the distinct knots of the base interval.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final t = Float64List.fromList([0, 0, 0, 0, 1, 2, 3, 3, 3, 3]);
final c = Float64List.fromList([0, 1, 3, -1, 2, 0]);
final s = BSpline(t, c, 3);
final p = s.toPPoly();
print('breakpoints ${p.x}');
print('pieces of degree ${p.k}; p(1.5) = ${p(1.5)}, s(1.5) = ${s(1.5)}');
}breakpoints [0.0, 1.0, 2.0, 3.0] pieces of degree 3; p(1.5) = 1.0312499999999996, s(1.5) = 1.03125
CatmullRomSpline
class CatmullRomSpline
A Catmull–Rom spline through points (count x dim, row-major). The parameter runs over [0, segments]; segment i joins point i to point i + 1 (closed curves join the last point back to the first). Open ends use reflected phantom points (P_{-1} = 2P_{0} - P_{1}).
Constructors
CatmullRomSpline(this.points, {required this.dim, this.alpha = 0.5, this.closed = false})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final pts = Float64List.fromList([0, 0, 1, 2, 3, 2, 4, 0, 6, 1]);
final cr = CatmullRomSpline(pts, dim: 2);
final open = [for (var i = 0; i <= 80; i++) cr.point(i / 20).toList()];
final loop = CatmullRomSpline(pts, dim: 2, closed: true);
final closed = [for (var i = 0; i <= 100; i++) loop.point(i / 20).toList()];
print('open: ${open.length} samples, closed: ${closed.length}');
}open: 81 samples, closed: 101
Properties
final Float64List pointsfinal int dimfinal int countfinal bool closedint get segmentsMethods
void pointInto(double s, Float64List out)The point at parameter s (in [0, segments]) into out.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final pts = Float64List.fromList([0, 0, 1, 2, 3, 2, 4, 0, 6, 1]);
final cr = CatmullRomSpline(pts, dim: 2, alpha: 0);
final out = Float64List(2);
for (final s in [0.0, 1.0, 1.5, 4.0]) {
cr.pointInto(s, out);
print('s = $s: (${out[0].toStringAsFixed(4)}, ${out[1].toStringAsFixed(4)})');
}
}s = 0.0: (0.0000, 0.0000) s = 1.0: (1.0000, 2.0000) s = 1.5: (2.0000, 2.2500) s = 4.0: (6.0000, 1.0000)
Float64List point(double s)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final pts = Float64List.fromList([0, 0, 1, 2, 3, 2, 4, 0, 6, 1]);
final series = <Map<String, Object>>[];
for (final a in [0.0, 0.5, 1.0]) {
final cr = CatmullRomSpline(pts, dim: 2, alpha: a);
series.add({'label': 'α = $a', 'points': [for (var i = 0; i <= 80; i++) cr.point(i / 20).toList()]});
}
print('uniform, centripetal and chordal parametrisations');
}uniform, centripetal and chordal parametrisations
GridInterpolator
class GridInterpolator
Tensor-product spline interpolation of values on the grid axes (values row-major, last axis fastest).
Constructors
GridInterpolator(List<Float64List> axes, Float64List values, {this.degree = 3, this.outside = GridOutside.nan})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final xs = Float64List.fromList([0, 1, 2, 3, 4]), ys = Float64List.fromList([0, 1, 2, 3]);
final v = Float64List.fromList([for (final x in xs) for (final y in ys) math.sin(x) * math.cos(y)]);
final g = GridInterpolator([xs, ys], v);
print('g(1.5, 0.5) = ${g([1.5, 0.5]).toStringAsFixed(5)}, exact ${(math.sin(1.5) * math.cos(0.5)).toStringAsFixed(5)}');
print('outside: ${g([5, 0])}');
}g(1.5, 0.5) = 0.87656, exact 0.87538 outside: NaN
Properties
final List<Float64List> axesfinal int dimsfinal int degreefinal GridOutside outsideMethods
double call(List<double> point, {List<int>? derivs})The value at point (length dims); derivs gives the derivative order along each axis (default none).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final xs = Float64List.fromList([0, 1, 2, 3]), ys = Float64List.fromList([0, 1, 2, 3]);
final v = Float64List.fromList([for (final x in xs) for (final y in ys) x * x + x * y]);
final g = GridInterpolator([xs, ys], v);
print('f(1.5, 2) = ${g([1.5, 2])}');
print('∂f/∂x = ${g([1.5, 2], derivs: [1, 0])} (exact 2x + y = 5)');
print('∂f/∂y = ${g([1.5, 2], derivs: [0, 1])} (exact x = 1.5)');
}f(1.5, 2) = 5.25 ∂f/∂x = 4.999999999999999 (exact 2x + y = 5) ∂f/∂y = 1.5 (exact x = 1.5)
GridOutside
enum GridOutside
Out-of-range behaviour of GridInterpolator.
Values
NurbsCurve
class NurbsCurve
Constructors
NurbsCurve(this.degree, this.knots, this.points, this.weights, {required this.dim})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// A quarter circle as a rational quadratic: middle weight √2/2.
final w = math.sqrt(2) / 2;
final q = NurbsCurve(2, Float64List.fromList([0, 0, 0, 1, 1, 1]), Float64List.fromList([1, 0, 1, 1, 0, 1]), Float64List.fromList([1, w, 1]), dim: 2);
final p = q.point(0.5);
print('midpoint (${p[0].toStringAsFixed(6)}, ${p[1].toStringAsFixed(6)}), radius ${math.sqrt(p[0] * p[0] + p[1] * p[1])}');
}midpoint (0.707107, 0.707107), radius 0.9999999999999999
factory NurbsCurve.fromBSpline(BSpline s)A non-rational B-spline curve as a NURBS curve (all weights 1).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final b = BSpline(Float64List.fromList([0, 0, 0, 1, 1, 1]), Float64List.fromList([0, 0, 1, 2, 2, 0]), 2, dim: 2);
final n = NurbsCurve.fromBSpline(b);
print('weights ${n.weights}');
final o = Float64List(2);
b.evalInto(0.3, o);
print('same point: ${n.point(0.3)} vs $o');
}weights [1.0, 1.0, 1.0] same point: [0.6000000000000001, 0.8400000000000001] vs [0.6, 0.84]
factory NurbsCurve.circle(List<double> center, double radius)The full circle of radius around center in the xy-plane (2-D or 3-D center): nine control points on the circumscribed square, degree 2, corner weights \frac{\sqrt{2}}{2}. Exact: every point is at distance radius, and the control points are exactly center + radius·(\pm1 or 0, \pm1 or 0) (four quarter turns; no trigonometry).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final c = NurbsCurve.circle([1, 2], 3);
var worst = 0.0;
for (var i = 0; i <= 100; i++) {
final p = c.point(i / 100);
worst = math.max(worst, (math.sqrt((p[0] - 1) * (p[0] - 1) + (p[1] - 2) * (p[1] - 2)) - 3).abs());
}
print('degree ${c.degree}, ${c.weights.length} control points, largest radius error ${worst < 1e-12 ? 'below 1e-12' : worst}');
print('length ${c.length().toStringAsFixed(10)} (2π·3 = ${(6 * math.pi).toStringAsFixed(10)})');
}degree 2, 9 control points, largest radius error below 1e-12 length 18.8495559215 (2π·3 = 18.8495559215)
factory NurbsCurve.arc(List<double> center, double radius, double start, double end, {List<double>? xAxis, List<double>? yAxis})The circular arc from start to end (radians, counter-clockwise, |end - start| \le 2\pi) of radius around center, in the plane spanned by xAxis and yAxis (unit, orthogonal; default the xy-plane). A7.1: one rational quadratic segment per \le 90^{\circ}. The radians form of NurbsCurve.arcTurns: the start and the per-segment turn enter through RatioBoundary.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final a = NurbsCurve.arc([0, 0], 2, 0, 2 * math.pi / 3);
final end = a.point(1);
print('end (${end[0].toStringAsFixed(6)}, ${end[1].toStringAsFixed(6)})');
print('length ${a.length().toStringAsFixed(8)} (4π/3 = ${(4 * math.pi / 3).toStringAsFixed(8)})');
}end (-1.000000, 1.732051) length 4.18879020 (4π/3 = 4.18879020)
factory NurbsCurve.arcTurns(List<double> center, double radius, Turn start, Turn step, int segments, {List<double>? xAxis, List<double>? yAxis})The circular arc of radius around center that starts at the direction start and makes segments steps of the turn step (at most a quarter turn: step.c ≥ 0), counter-clockwise in the plane of xAxis and yAxis. No trigonometry: the segment ends are start·\mathrm{step}^{i}; each middle control point is where the end tangents meet, radius·\frac{a_{i} + a_{i+1}}{1 + c}, rational in the ends; its weight is \cos(\frac{\Delta}{2}) = \sqrt{\frac{1 + c}{2}}, the one square root. With rational turns (Pythagorean triples) every control point is rational.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_math/ratio.ray' show Turn;
void main() {
// Start at 0 and take 3 steps of a quarter turn each, from turns instead of angles.
final a = NurbsCurve.arcTurns([0, 0], 1, Turn.unit(1, 0), Turn.unit(0, 1), 3);
for (final u in [0.0, 1 / 3, 2 / 3, 1.0]) {
final p = a.point(u);
print('u = ${u.toStringAsFixed(3)}: (${p[0].toStringAsFixed(6)}, ${p[1].toStringAsFixed(6)})');
}
}u = 0.000: (1.000000, 0.000000) u = 0.333: (0.000000, 1.000000) u = 0.667: (-1.000000, 0.000000) u = 1.000: (0.000000, -1.000000)
Properties
final int degreefinal int dimfinal Float64List knotsfinal Float64List pointsfinal Float64List weightsdouble get lowerdouble get upperMethods
void pointInto(double u, Float64List out)The point at parameter u into out (length dim).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final c = NurbsCurve.circle([0, 0], 1);
final out = Float64List(2);
c.pointInto(0.125, out);
print('point at 1/8 of the circle: $out');
}point at 1/8 of the circle: [0.7071067811865475, 0.7071067811865475]
Float64List point(double u)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final c = NurbsCurve.circle([0, 0], 1);
// The parameter is not proportional to angle on a rational circle.
final ang = [for (var i = 0; i <= 40; i++) (() { final p = c.point(i / 40); var a = math.atan2(p[1], p[0]); if (a < 0) a += 2 * math.pi; return [i / 40, a / (2 * math.pi)]; })()];
print('u = 0.1 -> angle/2π = ${ang[4][1].toStringAsFixed(4)}');
}u = 0.1 -> angle/2π = 0.0987
Float64List derivatives(double u, int order)Derivatives C^(0..order) at u (A4.2), as (order + 1) x dim row-major.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final c = NurbsCurve.circle([0, 0], 2);
final d = c.derivatives(0.1, 2);
print('C = (${d[0].toStringAsFixed(4)}, ${d[1].toStringAsFixed(4)})');
print('C′ = (${d[2].toStringAsFixed(4)}, ${d[3].toStringAsFixed(4)})');
print('C·C′ = ${(d[0] * d[2] + d[1] * d[3]).abs() < 1e-9 ? 0 : d[0] * d[2] + d[1] * d[3]} (tangent ⟂ radius)');
}C = (1.6277, 1.1622) C′ = (-7.6500, 10.7136) C·C′ = 0 (tangent ⟂ radius)
NurbsCurve insertKnot(double u, [int times = 1])The curve with knot u inserted times times (same shape, one more control point per insertion).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final c = NurbsCurve.circle([0, 0], 1);
final r = c.insertKnot(0.3);
print('${c.weights.length} -> ${r.weights.length} control points');
print('same point: ${(c.point(0.7)[0] - r.point(0.7)[0]).abs() < 1e-12}');
}9 -> 10 control points same point: true
double length([double? a, double? b])Arc length over [a, b] (default the whole curve): 8-point Gauss–Legendre per knot span, 4 subdivisions.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final c = NurbsCurve.circle([0, 0], 1);
print('full: ${c.length()}');
print('u in [0, 0.25]: ${c.length(0, 0.25)}');
}full: 6.283185307179587 u in [0, 0.25]: 1.570796326794897
NurbsSurface
class NurbsSurface
A NURBS surface: degrees p (u) and q (v), knots uKnots and vKnots, a control net of \nu \times nv points (row-major: point (i, j) at (i \cdot nv + j) \cdot \dim) and weights (\nu \times nv).
Constructors
NurbsSurface(this.p, this.q, this.uKnots, this.vKnots, this.points, this.weights, {required this.nu, required this.nv, this.dim = 3})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// A bilinear patch (degree 1 × 1): a saddle through 4 corners.
final s = NurbsSurface(1, 1, Float64List.fromList([0, 0, 1, 1]), Float64List.fromList([0, 0, 1, 1]),
Float64List.fromList([0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0]), Float64List.fromList([1, 1, 1, 1]), nu: 2, nv: 2);
print('centre ${s.point(0.5, 0.5)}');
}centre [0.5, 0.5, 0.5]
factory NurbsSurface.extrude(NurbsCurve curve, List<double> direction)The surface swept by moving curve along direction (degree 1 in v; a cylinder from a circle).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final c = NurbsCurve.circle([0, 0, 0], 1);
final cyl = NurbsSurface.extrude(c, [0, 0, 2]);
final p = cyl.point(0.25, 0.5);
print('point (${p[0].toStringAsFixed(4)}, ${p[1].toStringAsFixed(4)}, ${p[2]}), radius ${math.sqrt(p[0] * p[0] + p[1] * p[1])}');
}point (0.0000, 1.0000, 1.0), radius 1.0
factory NurbsSurface.revolve(NurbsCurve profile)The surface of revolution of a profile curve in the xz-plane (3-D points with y = 0, x \ge 0) about the z-axis, a full turn (A8.1): the profile is v, the circle is u. A semicircle gives an exact sphere.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Revolve the profile x = 1 + z²/2 (x, 0, z) about the z-axis: a vase.
final profile = NurbsCurve.fromBSpline(BSpline(Float64List.fromList([0, 0, 0, 1, 1, 1]), Float64List.fromList([1.5, 0, -1, 0.5, 0, 0, 1.5, 0, 1]), 2, dim: 3));
final vase = NurbsSurface.revolve(profile);
for (final v in [0.0, 0.5, 1.0]) {
final p = vase.point(0.1, v);
print('v = $v: radius ${math.sqrt(p[0] * p[0] + p[1] * p[1]).toStringAsFixed(4)}, z ${p[2].toStringAsFixed(4)}');
}
}v = 0.0: radius 1.5000, z -1.0000 v = 0.5: radius 1.0000, z 0.0000 v = 1.0: radius 1.5000, z 1.0000
Properties
final int pfinal int qfinal int nufinal int nvfinal int dimfinal Float64List uKnotsfinal Float64List vKnotsfinal Float64List pointsfinal Float64List weightsMethods
Float64List derivatives(double u, double v, int order)Partial derivatives S_{k, l}(u, v) for k + l <= order (A4.4): result[(k * (order + 1) + l) * \dim + d].
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final cyl = NurbsSurface.extrude(NurbsCurve.circle([0, 0, 0], 1), [0, 0, 3]);
final d = cyl.derivatives(0.1, 0.5, 1);
print('S = ${d.sublist(0, 3).map((x) => x.toStringAsFixed(4)).toList()}');
print('S_v = ${d.sublist(3, 6).map((x) => x.toStringAsFixed(4)).toList()}');
print('S_u = ${d.sublist(6, 9).map((x) => x.toStringAsFixed(4)).toList()}');
}S = [0.8138, 0.5811, 1.5000] S_v = [0.0000, 0.0000, 3.0000] S_u = [-3.8250, 5.3568, 0.0000]
Float64List point(double u, double v)The point S(u, v).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final cyl = NurbsSurface.extrude(NurbsCurve.circle([0, 0, 0], 1), [0, 0, 1]);
print(cyl.point(0, 0));
print(cyl.point(0.5, 1));
}[1.0, 0.0, 0.0] [-1.0, 0.0, 1.0]
Float64List normal(double u, double v)The unit normal Su \times Sv (3-D surfaces).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final cyl = NurbsSurface.extrude(NurbsCurve.circle([0, 0, 0], 1), [0, 0, 1]);
final p = cyl.point(0.2, 0.5), n = cyl.normal(0.2, 0.5);
print('normal ${n.map((x) => x.toStringAsFixed(4)).toList()}, parallel to the radius: ${(n[0] * p[1] - n[1] * p[0]).abs() < 1e-9}');
}normal [0.2938, 0.9559, -0.0000], parallel to the radius: true
NurbsSurface insertKnot(double value, {bool inU = true})The surface with value inserted once into the u knots (inU) or the v knots: every row/column of the net goes through curve knot insertion in homogeneous coordinates.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final cyl = NurbsSurface.extrude(NurbsCurve.circle([0, 0, 0], 1), [0, 0, 1]);
final r = cyl.insertKnot(0.5, inU: false);
print('v knots ${cyl.vKnots} -> ${r.vKnots}');
print('same point: ${(cyl.point(0.3, 0.7)[1] - r.point(0.3, 0.7)[1]).abs() < 1e-12}');
}v knots [0.0, 0.0, 1.0, 1.0] -> [0.0, 0.0, 0.5, 1.0, 1.0] same point: true
Extrapolate
enum Extrapolate
How a 1-D interpolant evaluates outside [x0, xn].
Values
PPoly
class PPoly
A piecewise polynomial in local power form: on [x[i], x[i + 1]], p(v) = \sum_{m} c[m]{}[i] (v - x[i])^{k - m}, degree k (SciPy's PPoly layout, highest power first).
Constructors
PPoly(this.x, this.c, {this.extrapolate = Extrapolate.extend})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Two cubic pieces on [0, 1] and [1, 2]; rows are coefficients of (x − x_i)^3, ^2, ^1, ^0.
final p = PPoly(Float64List.fromList([0, 1, 2]), [
Float64List.fromList([1, -2]),
Float64List.fromList([0, 3]),
Float64List.fromList([-1, 2]),
Float64List.fromList([0, 0]),
]);
print('degree ${p.k}, p(0.5) = ${p(0.5)}, p(1.5) = ${p(1.5)}');
}degree 3, p(0.5) = -0.375, p(1.5) = 1.5
Properties
final int kfinal Extrapolate extrapolatedouble get lowerdouble get upperMethods
double call(double v, [int nu = 0])The nuth derivative at v.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Two cubic pieces on [0, 1] and [1, 2]; rows are coefficients of (x − x_i)^3, ^2, ^1, ^0.
final p = PPoly(Float64List.fromList([0, 1, 2]), [
Float64List.fromList([1, -2]),
Float64List.fromList([0, 3]),
Float64List.fromList([-1, 2]),
Float64List.fromList([0, 0]),
]);
print('p(1.5) = ${p(1.5)}, p\'(1.5) = ${p(1.5, 1)}');
print('extrapolated p(2.5) = ${p(2.5)}');
}p(1.5) = 1.5, p'(1.5) = 3.5 extrapolated p(2.5) = 3.0
Float64List evalAll(Float64List v, [int nu = 0])Evaluates at every point of v into a new list.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Two cubic pieces on [0, 1] and [1, 2]; rows are coefficients of (x − x_i)^3, ^2, ^1, ^0.
final p = PPoly(Float64List.fromList([0, 1, 2]), [
Float64List.fromList([1, -2]),
Float64List.fromList([0, 3]),
Float64List.fromList([-1, 2]),
Float64List.fromList([0, 0]),
]);
print(p.evalAll(Float64List.fromList([0, 0.5, 1, 1.5, 2])));
}[0.0, -0.375, 0.0, 1.5, 3.0]
PPoly derivative([int nu = 1])The derivative as a new piecewise polynomial of degree k - 1.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Two cubic pieces on [0, 1] and [1, 2]; rows are coefficients of (x − x_i)^3, ^2, ^1, ^0.
final p = PPoly(Float64List.fromList([0, 1, 2]), [
Float64List.fromList([1, -2]),
Float64List.fromList([0, 3]),
Float64List.fromList([-1, 2]),
Float64List.fromList([0, 0]),
]);
final d = p.derivative();
print('degree ${d.k}; d(0.5) = ${d(0.5)}');
}degree 2; d(0.5) = -0.25
PPoly antiderivative()The antiderivative that is 0 at x[0] and continuous, degree k + 1.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Two cubic pieces on [0, 1] and [1, 2]; rows are coefficients of (x − x_i)^3, ^2, ^1, ^0.
final p = PPoly(Float64List.fromList([0, 1, 2]), [
Float64List.fromList([1, -2]),
Float64List.fromList([0, 3]),
Float64List.fromList([-1, 2]),
Float64List.fromList([0, 0]),
]);
final a = p.antiderivative();
print('degree ${a.k}; ∫₀² p = ${a(2) - a(0)}');
}degree 4; ∫₀² p = 1.25
double integrate(double a, double b)\int_{a}^{b} p (with the same extrapolation rule; periodic integrates whole periods exactly).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Two cubic pieces on [0, 1] and [1, 2]; rows are coefficients of (x − x_i)^3, ^2, ^1, ^0.
final p = PPoly(Float64List.fromList([0, 1, 2]), [
Float64List.fromList([1, -2]),
Float64List.fromList([0, 3]),
Float64List.fromList([-1, 2]),
Float64List.fromList([0, 0]),
]);
print('∫₀² p = ${p.integrate(0, 2)}');
print('∫₂⁰ p = ${p.integrate(2, 0)}');
}∫₀² p = 1.25 ∫₂⁰ p = -1.25
List<double> solve([double y = 0])Real roots of p(v) = y on the breakpoint range (each interval's cubic or lower solved by bracketing; for degree ≤ 3). Sorted, duplicates at breakpoints removed.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Two cubic pieces on [0, 1] and [1, 2]; rows are coefficients of (x − x_i)^3, ^2, ^1, ^0.
final p = PPoly(Float64List.fromList([0, 1, 2]), [
Float64List.fromList([1, -2]),
Float64List.fromList([0, 3]),
Float64List.fromList([-1, 2]),
Float64List.fromList([0, 0]),
]);
final roots = p.solve();
print('roots of p: $roots');
print('where p = 0.2: ${p.solve(0.2)}');
}roots of p: [0.0, 1.0] where p = 0.2: [1.0888579869569162]
CubicHermiteSpline
class CubicHermiteSpline extends PPoly
Piecewise cubic Hermite interpolation from values y and slopes dydx at x (SciPy's CubicHermiteSpline).
Constructors
CubicHermiteSpline(Float64List x, Float64List y, Float64List dydx, {super.extrapolate})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2, 3]);
final y = Float64List.fromList([0, 1, 0, 1]);
final d = Float64List.fromList([0, 0, 0, 0]); // flat at every point
final h = CubicHermiteSpline(x, y, d);
print('h(0.5) = ${h(0.5)}, h\'(1) = ${h(1, 1)}');
}h(0.5) = 0.5, h'(1) = 0.0
SplineBoundary
sealed class SplineBoundary
A boundary condition of a CubicSpline.
Constructors
const SplineBoundary()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2, 3, 4, 5, 6]);
final y = Float64List.fromList([for (final v in x) math.sin(v)]);
// The built-in boundary conditions are constants; FirstDerivative and SecondDerivative take a value.
for (final (name, b) in [('notAKnot', SplineBoundary.notAKnot), ('natural', SplineBoundary.natural), ('clamped', SplineBoundary.clamped)]) {
final s = CubicSpline(x, y, left: b);
print('${name.padRight(9)} s\'(0) = ${s(0, 1).toStringAsFixed(4)}, s\'\'(0) = ${s(0, 2).toStringAsFixed(4)}');
}
}notAKnot s'(0) = 1.1455, s''(0) = -0.5253 natural s'(0) = 0.9937, s''(0) = 0.0000 clamped s'(0) = 0.0000, s''(0) = 3.4400
Static
static const notAKnot = _NotAKnot()The first and second piece are the same cubic (the third derivative is continuous at x[1]); SciPy's default.
static const periodic = _Periodic()Periodic (y[0] must equal y[n - 1]); set on both ends.
FirstDerivative
final class FirstDerivative extends SplineBoundary
A prescribed first derivative at the end.
Constructors
const FirstDerivative(this.value)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2, 3, 4, 5, 6]);
final y = Float64List.fromList([for (final v in x) math.sin(v)]);
final s = CubicSpline(x, y, left: const FirstDerivative(1), right: FirstDerivative(math.cos(6)));
print('s\'(0) = ${s(0, 1)}, s\'(6) = ${s(6, 1).toStringAsFixed(6)}');
print('error at 2.5: ${(s(2.5) - math.sin(2.5)).abs().toStringAsExponential(2)}');
}s'(0) = 1.0, s'(6) = 0.960170 error at 2.5: 1.89e-3
Properties
final double valueSecondDerivative
final class SecondDerivative extends SplineBoundary
A prescribed second derivative at the end.
Constructors
const SecondDerivative(this.value)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2, 3, 4, 5, 6]);
final y = Float64List.fromList([for (final v in x) math.sin(v)]);
final s = CubicSpline(x, y, left: const SecondDerivative(0), right: const SecondDerivative(0));
print('natural: s\'\'(0) = ${s(0, 2)}, s\'\'(6) = ${s(6, 2)}');
}natural: s''(0) = 4.440892098500626e-16, s''(6) = -2.220446049250313e-16
Properties
final double valueCubicSpline
class CubicSpline extends CubicHermiteSpline
Cubic spline interpolation, twice continuously differentiable (SciPy's CubicSpline: slopes from a tridiagonal system, solved here by banded LU with pivoting since not-a-knot rows are not diagonally dominant).
import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
void main() {
final xs = Float64List.fromList([for (var i = 0; i <= 8; i++) i * math.pi / 8]);
final ys = Float64List.fromList([for (final x in xs) math.sin(x)]);
final s = CubicSpline(xs, ys);
print('spline(1.0) = ${s(1.0).toStringAsFixed(6)}, sin(1.0) = ${math.sin(1.0).toStringAsFixed(6)}');
print('integral over [0, π] = ${s.integrate(0, math.pi).toStringAsFixed(6)} (exact 2)');
{'label': 'spline', 'points': [for (var i = 0; i <= 64; i++) [i * math.pi / 64, s(i * math.pi / 64)]]},
{'label': 'samples', 'style': 'points', 'points': [for (var i = 0; i < xs.length; i++) [xs[i], ys[i]]]},
]})}');
}spline(1.0) = 0.841436, sin(1.0) = 0.841471 integral over [0, π] = 2.000037 (exact 2)
Constructors
factory CubicSpline(Float64List x, Float64List y, {SplineBoundary left = SplineBoundary.notAKnot, SplineBoundary? right, Extrapolate? extrapolate})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2, 3, 4, 5, 6]);
final y = Float64List.fromList([for (final v in x) math.sin(v)]);
final nak = CubicSpline(x, y);
final nat = CubicSpline(x, y, left: SplineBoundary.natural);
print('not-a-knot s(2.5) = ${nak(2.5).toStringAsFixed(6)}');
print('natural s(2.5) = ${nat(2.5).toStringAsFixed(6)}');
print('sin 2.5 = ${math.sin(2.5).toStringAsFixed(6)}');
}not-a-knot s(2.5) = 0.598744 natural s(2.5) = 0.596223 sin 2.5 = 0.598472
PchipInterpolator
class PchipInterpolator extends CubicHermiteSpline
Shape-preserving monotone piecewise cubic (Fritsch–Carlson slopes with SciPy's weighted harmonic mean and three-point end slopes; PchipInterpolator). Never overshoots monotone data.
Constructors
PchipInterpolator(Float64List x, Float64List y, {super.extrapolate})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2, 3, 4, 5, 6]);
final y = Float64List.fromList([0, 0, 0, 1, 1, 1, 1]); // a step
final p = PchipInterpolator(x, y);
final c = CubicSpline(x, y);
print('pchip stays in [0, 1]: ${[for (var i = 0; i <= 60; i++) p(i / 10)].every((v) => v >= 0 && v <= 1)}');
print('cubic spline overshoots: min ${[for (var i = 0; i <= 60; i++) c(i / 10)].reduce(math.min).toStringAsFixed(4)}');
}pchip stays in [0, 1]: true cubic spline overshoots: min -0.1303
AkimaInterpolator
class AkimaInterpolator extends CubicHermiteSpline
Akima's 1970 interpolant (and the modified "makima" variant, which avoids overshoot on flat runs): slopes from a weighted average of neighbouring secants (SciPy's Akima1DInterpolator; out-of-range is NaN by default).
Constructors
AkimaInterpolator(Float64List x, Float64List y, {bool modified = false, super.extrapolate = Extrapolate.nan})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 2, 3, 4, 5, 6]);
final y = Float64List.fromList([0, 0, 0, 1, 1, 1, 1]); // a step
final a = AkimaInterpolator(x, y);
final m = AkimaInterpolator(x, y, modified: true);
print('akima(2.5) = ${a(2.5).toStringAsFixed(4)}, makima(2.5) = ${m(2.5).toStringAsFixed(4)}');
}akima(2.5) = 0.5000, makima(2.5) = 0.5000
LinearInterpolator
class LinearInterpolator
Piecewise linear interpolation with a choice of out-of-range behaviour (numpy.interp clamps; SciPy's interp1d extrapolates or fills).
Constructors
LinearInterpolator(this.x, this.y, {this.outside = LinearOutside.clamp})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 3]), y = Float64List.fromList([0, 2, 1]);
for (final o in LinearOutside.values.where((o) => o != LinearOutside.error)) {
final f = LinearInterpolator(x, y, outside: o);
print('${o.name.padRight(11)} f(4) = ${f(4)}');
}
}clamp f(4) = 1.0 extrapolate f(4) = 0.5 nan f(4) = NaN
Properties
final Float64List xfinal Float64List yfinal LinearOutside outsideMethods
double call(double v)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = Float64List.fromList([0, 1, 3]), y = Float64List.fromList([0, 2, 1]);
final f = LinearInterpolator(x, y, outside: LinearOutside.extrapolate);
print('f(0.5) = ${f(0.5)}, f(2) = ${f(2)}, f(4) = ${f(4)}');
}f(0.5) = 1.0, f(2) = 1.5, f(4) = 0.5
LinearOutside
enum LinearOutside
Out-of-range behaviour of LinearInterpolator.
Values
clampextrapolatenanerrorRbfKernel
enum RbfKernel
RBF kernels \varphi(r), r = \varepsilon\Vert x - y\Vert (SciPy's names and signs).
Values
linear(0, true)thinPlateSpline(1, true)cubic(1, true)quintic(2, true)multiquadric(0, false)inverseMultiquadric(-1, false)inverseQuadratic(-1, false)gaussian(-1, false)Constructors
const RbfKernel(this.minDegree, this.scaleInvariant)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
for (final k in RbfKernel.values) {
print('${k.name.padRight(20)} min degree ${k.minDegree.toString().padLeft(2)}, scale invariant ${k.scaleInvariant}');
}
}linear min degree 0, scale invariant true thinPlateSpline min degree 1, scale invariant true cubic min degree 1, scale invariant true quintic min degree 2, scale invariant true multiquadric min degree 0, scale invariant false inverseMultiquadric min degree -1, scale invariant false inverseQuadratic min degree -1, scale invariant false gaussian min degree -1, scale invariant false
Properties
final int minDegreeThe lowest polynomial degree that keeps the system solvable (-1: none needed).
final bool scaleInvariantWhether \varepsilon has no effect (it may then be left at 1).
Methods
double phi(double r)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
for (final k in [RbfKernel.thinPlateSpline, RbfKernel.cubic, RbfKernel.gaussian]) {
print('${k.name}: φ(1) = ${k.phi(1)}, φ(2) = ${k.phi(2).toStringAsFixed(6)}');
}
}thinPlateSpline: φ(1) = 0.0, φ(2) = 2.772589 cubic: φ(1) = 1.0, φ(2) = 8.000000 gaussian: φ(1) = 0.36787944117144233, φ(2) = 0.018316
RbfInterpolator
class RbfInterpolator
An RBF interpolant s(x) = \sum c_{i} \varphi(\varepsilon\Vert x - y_{i}\Vert) + \sum b_{j} p_{j}(x) through values at centers (n x dim). values may carry outputs values per centre. smoothing > 0 gives a smoothing (not interpolating) fit. degree defaults to max(0, kernel minimum) as in SciPy.
Constructors
RbfInterpolator(this.centers, Float64List values, {required this.dim, this.kernel = RbfKernel.thinPlateSpline, double? epsilon, this.smoothing = 0, int? degree, this.outputs = 1})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Scattered 2-D samples of f(x, y) = x·y.
final rng = math.Random(11);
final c = Float64List.fromList([for (var i = 0; i < 40; i++) rng.nextDouble() * 2 - 1]);
final v = Float64List.fromList([for (var i = 0; i < 20; i++) c[2 * i] * c[2 * i + 1]]);
final r = RbfInterpolator(c, v, dim: 2);
print('r(0.5, 0.5) = ${r([0.5, 0.5]).toStringAsFixed(4)} (exact 0.25)');
}r(0.5, 0.5) = 0.2654 (exact 0.25)
Properties
final Float64List centersfinal int dimfinal int nfinal int degreefinal int outputsfinal RbfKernel kernelfinal double epsilonfinal double smoothingMethods
void evalInto(Float64List x, Float64List out)The interpolant at x (length dim) into out (length outputs).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Scattered 2-D samples of f(x, y) = x·y.
final rng = math.Random(11);
final c = Float64List.fromList([for (var i = 0; i < 40; i++) rng.nextDouble() * 2 - 1]);
final v = Float64List.fromList([for (var i = 0; i < 20; i++) c[2 * i] * c[2 * i + 1]]);
final r = RbfInterpolator(c, v, dim: 2);
final out = Float64List(1);
r.evalInto(Float64List.fromList([0.2, -0.4]), out);
print('r(0.2, −0.4) = ${out[0].toStringAsFixed(4)} (exact −0.08)');
}r(0.2, −0.4) = -0.0882 (exact −0.08)
double call(List<double> x)The (first output of the) interpolant at x.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Scattered 2-D samples of f(x, y) = x·y.
final rng = math.Random(11);
final c = Float64List.fromList([for (var i = 0; i < 40; i++) rng.nextDouble() * 2 - 1]);
final v = Float64List.fromList([for (var i = 0; i < 20; i++) c[2 * i] * c[2 * i + 1]]);
final r = RbfInterpolator(c, v, dim: 2);
print('at a data point: ${(r([c[0], c[1]]) - v[0]).abs() < 1e-9}');
print('r(0, 0) = ${r([0, 0]).toStringAsFixed(4)}');
}at a data point: true r(0, 0) = 0.0046
class SingularMatrixException implements Exception
Thrown when a factorisation meets a singular (or, for Cholesky, non-positive-definite) matrix.
Constructors
SingularMatrixException(this.message)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
try {
DenseLu(Float64List.fromList([1, 2, 2, 4]), 2);
} on SingularMatrixException catch (e) {
print('caught: ${e.message}');
}
}caught: zero pivot in column 1
Properties
final String messageMethods
String toString()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print(SingularMatrixException('zero pivot in column 1'));
}SingularMatrixException: zero pivot in column 1
DenseLu
final class DenseLu
LU factorisation with partial pivoting of an n \times n row-major matrix, P A = L U, stored in place (L unit lower).
Constructors
DenseLu(Float64List a, this.n, {bool inPlace = false})Factors a (n \times n, row-major). a is copied unless inPlace.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final a = Float64List.fromList([4, 3, 0, 3, 4, -1, 0, -1, 4]); // 3 × 3, row-major
final lu = DenseLu(a, 3);
final x = lu.solve(Float64List.fromList([24, 30, -24]));
print('x = ${x.map((v) => v.toStringAsFixed(6)).toList()}');
}x = [3.000000, 4.000000, -5.000000]
Properties
final int nfinal Float64List lufinal Int32List pivdouble get determinantMethods
void solveInPlace(Float64List b)Solves A x = b in place in b.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final a = Float64List.fromList([4, 3, 0, 3, 4, -1, 0, -1, 4]); // 3 × 3, row-major
final lu = DenseLu(a, 3);
final b = Float64List.fromList([1, 0, 0]);
lu.solveInPlace(b);
print('first column of A⁻¹: ${b.map((v) => v.toStringAsFixed(6)).toList()}');
}first column of A⁻¹: [0.625000, -0.500000, -0.125000]
Float64List solve(Float64List b)A new vector x with A x = b.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final a = Float64List.fromList([4, 3, 0, 3, 4, -1, 0, -1, 4]); // 3 × 3, row-major
final lu = DenseLu(a, 3);
for (final b in [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) {
print(lu.solve(Float64List.fromList(b)).map((v) => v.toStringAsFixed(4)).toList());
}
}[0.6250, -0.5000, -0.1250] [-0.5000, 0.6667, 0.1667] [-0.1250, 0.1667, 0.2917]
double rcondEstimate(double anorm1)Reciprocal condition estimate in the 1-norm from the factors (cheap lower bound on \frac{1}{\operatorname{cond}}, LAPACK dgecon-like: one solve with a +-1 right-hand side). Used by the solvers to decide when to refactor or regularise.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
for (final eps in [1.0, 1e-4, 1e-10]) {
final a = Float64List.fromList([1, 1, 1, 1 + eps]);
final anorm = 2 + eps; // the 1-norm of a
print('eps $eps: rcond ≈ ${DenseLu(a, 2).rcondEstimate(anorm).toStringAsExponential(3)}');
}
}eps 1.0: rcond ≈ 1.333e-1 eps 0.0001: rcond ≈ 2.500e-5 eps 1e-10: rcond ≈ 2.500e-11
DenseCholesky
final class DenseCholesky
Cholesky factorisation A = L L^{T} of a symmetric positive-definite row-major matrix (lower triangle used).
Constructors
DenseCholesky(Float64List a, this.n)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final a = Float64List.fromList([4, 2, 2, 3]);
final c = DenseCholesky(a, 2);
final b = Float64List.fromList([2, 1]);
c.solveInPlace(b);
print('x = $b');
}x = [0.5, 0.0]
Properties
final int nfinal Float64List lMethods
void solveInPlace(Float64List b)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final c = DenseCholesky(Float64List.fromList([2, -1, 0, -1, 2, -1, 0, -1, 2]), 3);
final b = Float64List.fromList([1, 1, 1]);
c.solveInPlace(b);
print('x = $b');
}x = [1.5, 2.000000000000001, 1.5000000000000002]
DenseQr
final class DenseQr
Householder QR of an m \times n (m \ge n) row-major matrix; solves least squares min \Vert A x - b\Vert_{2}. R and the reflectors (LAPACK dgeqrf layout, H = I - \tau v v^{T}) come from riptide_numerics_cpu' blocked geqrf.
Constructors
DenseQr(Float64List a, this.m, this.n)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Least squares: fit y = c0 + c1 t through 4 points.
final a = Float64List.fromList([1, 0, 1, 1, 1, 2, 1, 3]);
final y = Float64List.fromList([1, 2.9, 5.1, 7]);
final c = DenseQr(a, 4, 2).solve(y);
print('intercept ${c[0].toStringAsFixed(4)}, slope ${c[1].toStringAsFixed(4)}');
}intercept 0.9700, slope 2.0200
Properties
final int mfinal int nfinal Float64List qrfinal Float64List tauMethods
void applyQt(Float64List b)Applies Q^{T} to b (length m) in place.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Least squares: fit y = c0 + c1 t through 4 points.
final a = Float64List.fromList([1, 0, 1, 1, 1, 2, 1, 3]);
final y = Float64List.fromList([1, 2.9, 5.1, 7]);
final qr = DenseQr(a, 4, 2);
final b = Float64List.fromList(y);
qr.applyQt(b);
print('Qᵀy = ${b.map((v) => v.toStringAsFixed(4)).toList()}');
print('residual norm = ${math.sqrt(b[2] * b[2] + b[3] * b[3]).toStringAsFixed(4)}');
}Qᵀy = [-8.0000, -4.5169, 0.1247, 0.0494] residual norm = 0.1342
Float64List solve(Float64List b)The least-squares solution x (length n) of A x \approx b.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Least squares: fit y = c0 + c1 t through 4 points.
final a = Float64List.fromList([1, 0, 1, 1, 1, 2, 1, 3]);
final y = Float64List.fromList([1, 2.9, 5.1, 7]);
print(DenseQr(a, 4, 2).solve(y));
}[0.9699999999999989, 2.02]
BdfStepper
final class BdfStepper extends OdeStepper
Variable-order BDF stepper (SciPy's BDF). jac analytic, else finite differences (FiniteDifferenceJacobian); for an automatic Jacobian pass odeJacobianFromDual(...) as jac.
Constructors
BdfStepper(this.f, double t0, Float64List y0, this.tBound, {this.jac, double rtol = 1e-3, Object atol = 1e-6, this.maxStep = double.infinity, double? firstStep})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Robertson's stiff chemistry problem.
void f(double t, Float64List y, Float64List dy) {
dy[0] = -0.04 * y[0] + 1e4 * y[1] * y[2];
dy[1] = 0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] * y[1];
dy[2] = 3e7 * y[1] * y[1];
}
final s = BdfStepper(f, 0, Float64List.fromList([1, 0, 0]), 40, rtol: 1e-6, atol: 1e-10);
var steps = 0;
final pts = <List<double>>[];
while (s.step()) {
steps++;
pts.add([s.t, s.y[0]]);
if (s.t >= 40) break;
}
print('BdfStepper: $steps steps to t = 40, y = ${s.y.map((v) => v.toStringAsExponential(4)).toList()}');
}BdfStepper: 144 steps to t = 40, y = [7.1583e-1, 9.1856e-6, 2.8416e-1]
Properties
final OdeFunction ffinal OdeJacobianFunction? jacfinal double tBoundfinal double maxStepfinal double directionfinal int nlate final double rtollate final Float64List atollate final double newtonTolint orderdouble get tFloat64List get ydouble get tOlddouble get stepSizeMethods
bool step()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = BdfStepper(f, 0, Float64List.fromList([1, 0]), 6, rtol: 1e-6);
var n = 0;
while (s.step()) {
n++;
if (s.t >= 6) break;
}
print('$n steps; y(6) = ${s.y[0].toStringAsFixed(6)}, cos 6 = ${math.cos(6).toStringAsFixed(6)}');
}64 steps; y(6) = 0.960152, cos 6 = 0.960170
void denseInto(double time, Float64List out)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = BdfStepper(f, 0, Float64List.fromList([1, 0]), 3, rtol: 1e-6);
s.step();
s.step();
final mid = (s.tOld + s.t) / 2, out = Float64List(2);
s.denseInto(mid, out);
print('between ${s.tOld.toStringAsFixed(4)} and ${s.t.toStringAsFixed(4)}: y(${mid.toStringAsFixed(4)}) = ${out[0].toStringAsFixed(6)} (cos = ${math.cos(mid).toStringAsFixed(6)})');
}between 0.0001 and 0.0002: y(0.0002) = 1.000000 (cos = 1.000000)
DenseSegment denseSegment()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = BdfStepper(f, 0, Float64List.fromList([1, 0]), 6, rtol: 1e-6);
final segs = <DenseSegment>[];
while (s.step()) {
segs.add(s.denseSegment());
if (s.t >= 6) break;
}
final out = Float64List(2);
final pts = <List<double>>[];
for (final g in segs) {
for (var k = 0; k < 4; k++) {
final t = g.tMin + (g.tMax - g.tMin) * k / 4;
g.evaluate(t, out);
pts.add([t, out[0]]);
}
}
print('${segs.length} segments');
}64 segments
OdeStatus
enum OdeStatus
Why a stepper stopped.
Values
runningfinishedfailedOdeStepper
abstract class OdeStepper
An incremental solver: call step until status is not OdeStatus.running. Each step reuses the stepper's own buffers; y is valid until the next step. denseInto evaluates the last step's interpolant without allocating.
Properties
Float64List get yint get nOdeStatus statusString? messageint nfevint njevint nluMethods
bool step()Advances one accepted step (or to the bound). Returns false on failure (message says why).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final OdeStepper s = createStepper(OdeMethod.tsit5, f, 0, Float64List.fromList([1, 0]), 10, rtol: 1e-8);
var n = 0;
while (s.step()) {
n++;
if (s.t >= 10) break;
}
print('tsit5: $n steps, last step size ${s.stepSize.toStringAsFixed(4)}');
}tsit5: 36 steps, last step size 0.2876
void denseInto(double time, Float64List out)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = createStepper(OdeMethod.rk45, f, 0, Float64List.fromList([1, 0]), 2);
s.step();
final out = Float64List(2);
s.denseInto(s.t / 2, out);
print('y at half the first step: ${out[0].toStringAsFixed(8)} (cos ${math.cos(s.t / 2).toStringAsFixed(8)})');
}y at half the first step: 0.99999988 (cos 0.99999988)
DenseSegment denseSegment()A copy of the last step's interpolant, valid after later steps (for OdeSolution.sol).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = createStepper(OdeMethod.rk45, f, 0, Float64List.fromList([1, 0]), 2);
s.step();
final seg = s.denseSegment();
print('segment [${seg.tMin}, ${seg.tMax.toStringAsFixed(4)}]');
}segment [0.0, 0.0010]
DenseSegment
abstract class DenseSegment
One step's continuous extension.
Properties
double get tMindouble get tMaxMethods
void evaluate(double t, Float64List out)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = createStepper(OdeMethod.rk45, f, 0, Float64List.fromList([1, 0]), 6, rtol: 1e-3);
s.step();
final seg = s.denseSegment();
final out = Float64List(2);
final pts = [for (var k = 0; k <= 20; k++) (() { final t = seg.tMin + (seg.tMax - seg.tMin) * k / 20; seg.evaluate(t, out); return [t, out[0]]; })()];
print('one coarse step to ${seg.tMax.toStringAsFixed(4)}, sampled at 21 points');
}one coarse step to 0.0010, sampled at 21 points
final class FiniteDifferenceJacobian
A finite-difference Jacobian: forward differences with SciPy's step rule h_{j} = \mathrm{sqrt}(eps)·\max(|y_{j}|, \mathrm{atol}_{j}) (num_jac without its adaptive refinement). Costs n evaluations of f; fy is f(t, y).
Constructors
FiniteDifferenceJacobian(this.f, this.n, this.atol)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final j = FiniteDifferenceJacobian(f, 2, Float64List.fromList([1e-8, 1e-8]));
final y = Float64List.fromList([1, 0.5]), fy = Float64List(2), jac = Float64List(4);
f(0, y, fy);
j(0, y, fy, jac);
print('J ≈ ${jac.map((v) => v.toStringAsFixed(6)).toList()}');
}J ≈ [0.000000, 1.000000, -1.000000, -0.000000]
Properties
final OdeFunction ffinal int nfinal Float64List atolint nfevMethods
void call(double t, Float64List y, Float64List fy, Float64List jac)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) => dy[0] = y[0] * y[0];
final j = FiniteDifferenceJacobian(f, 1, Float64List.fromList([1e-10]));
final jac = Float64List(1), fy = Float64List(1);
for (final v in [1.0, 2.0, 3.0]) {
final y = Float64List.fromList([v]);
f(0, y, fy);
j(0, y, fy, jac);
print('d(y²)/dy at $v ≈ ${jac[0].toStringAsFixed(6)}');
}
}d(y²)/dy at 1.0 ≈ 2.000000 d(y²)/dy at 2.0 ≈ 4.000000 d(y²)/dy at 3.0 ≈ 6.000000
EnsembleMethod
enum EnsembleMethod
Values
EnsembleIntegrator
final class EnsembleIntegrator
Fixed-step integration of n systems of dimension d stored structure-of-arrays (y[k \cdot n + i]); f receives and fills the whole batch. step allocates nothing.
Constructors
EnsembleIntegrator(this.f, this.n, this.d, {this.method = EnsembleMethod.rk4})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 4 harmonic oscillators with different frequencies, structure-of-arrays: x0..x3, v0..v3.
final w = [1.0, 2.0, 3.0, 4.0];
void f(double t, Float64List y, Float64List dy) {
for (var i = 0; i < 4; i++) {
dy[i] = y[4 + i];
dy[4 + i] = -w[i] * w[i] * y[i];
}
}
final y = Float64List.fromList([1, 1, 1, 1, 0, 0, 0, 0]);
final e = EnsembleIntegrator(f, 4, 2);
final traj = [for (var i = 0; i < 4; i++) <List<double>>[[0, 1]]];
var t = 0.0;
for (var s = 0; s < 100; s++) {
e.step(t, y, 0.03);
t += 0.03;
for (var i = 0; i < 4; i++) {
traj[i].add([t, y[i]]);
}
}
print('x(3) = ${[for (var i = 0; i < 4; i++) y[i].toStringAsFixed(4)]}');
print('cos(3ω) = ${[for (final o in w) math.cos(3 * o).toStringAsFixed(4)]}');
}x(3) = [-0.9900, 0.9602, -0.9111, 0.8438] cos(3ω) = [-0.9900, 0.9602, -0.9111, 0.8439]
Properties
final OdeFunction ffinal int nfinal int dfinal EnsembleMethod methodfinal Float64List errorEstimateFor EnsembleMethod.dopri5: after each step, \max_{k} |local error| of each system.
int get nfevMethods
void step(double t, Float64List y, double h)Advances y (length n \cdot d) from t by h.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 4 harmonic oscillators with different frequencies, structure-of-arrays: x0..x3, v0..v3.
final w = [1.0, 2.0, 3.0, 4.0];
void f(double t, Float64List y, Float64List dy) {
for (var i = 0; i < 4; i++) {
dy[i] = y[4 + i];
dy[4 + i] = -w[i] * w[i] * y[i];
}
}
final y = Float64List.fromList([1, 1, 1, 1, 0, 0, 0, 0]);
final e = EnsembleIntegrator(f, 4, 2, method: EnsembleMethod.dopri5);
e.step(0, y, 0.1);
print('after one dopri5 step: ${y.map((v) => v.toStringAsFixed(6)).toList()}');
}after one dopri5 step: [0.995004, 0.980067, 0.955336, 0.921060, -0.099833, -0.397339, -0.886561, -1.557675]
double integrate(double t0, Float64List y, double h, int steps)steps steps of size h from t0. Returns the final time.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 4 harmonic oscillators with different frequencies, structure-of-arrays: x0..x3, v0..v3.
final w = [1.0, 2.0, 3.0, 4.0];
void f(double t, Float64List y, Float64List dy) {
for (var i = 0; i < 4; i++) {
dy[i] = y[4 + i];
dy[4 + i] = -w[i] * w[i] * y[i];
}
}
final y = Float64List.fromList([1, 1, 1, 1, 0, 0, 0, 0]);
final t = EnsembleIntegrator(f, 4, 2).integrate(0, y, 0.01, 300);
print('t = $t: x = ${[for (var i = 0; i < 4; i++) y[i].toStringAsFixed(5)]}');
}t = 3.0: x = [-0.98999, 0.96017, -0.91113, 0.84385]
Rk4Stepper
final class Rk4Stepper
Classic fourth-order Runge–Kutta with a fixed step. step allocates nothing.
Constructors
Rk4Stepper(this.f, this.n)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = Rk4Stepper(f, 2);
final y = Float64List.fromList([1, 0]);
final pts = <List<double>>[[1, 0]];
for (var i = 0; i < 63; i++) {
s.step(i * 0.1, y, 0.1);
pts.add([y[0], y[1]]);
}
print('after 63 steps of 0.1: (${y[0].toStringAsFixed(6)}, ${y[1].toStringAsFixed(6)})');
}after 63 steps of 0.1: (0.999858, -0.016809)
Properties
final OdeFunction ffinal int nint nfevMethods
void step(double t, Float64List y, double h)Advances y in place from t by h.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = Rk4Stepper(f, 2);
for (final h in [0.5, 0.25, 0.125]) {
final y = Float64List.fromList([1, 0]);
for (var i = 0; i < (2 / h).round(); i++) {
s.step(i * h, y, h);
}
print('h = $h: error at t = 2 ${(y[0] - math.cos(2)).abs().toStringAsExponential(3)}');
}
}h = 0.5: error at t = 2 1.039e-3 h = 0.25: error at t = 2 6.348e-5 h = 0.125: error at t = 2 3.855e-6
double integrate(double t0, Float64List y, double h, int steps)steps steps of size h from t0; y is advanced in place. Returns the final time.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final y = Float64List.fromList([1, 0]);
final t = Rk4Stepper(f, 2).integrate(0, y, 0.01, 628);
print('t = ${t.toStringAsFixed(2)}: y = ${y[0].toStringAsFixed(8)}');
}t = 6.28: y = 0.99999493
RkTableau
final class RkTableau
A Butcher tableau of an explicit embedded pair with FSAL (the last stage is f at the new point).
Constructors
const RkTableau({required this.name, required this.order, required this.errorOrder, required this.c, required this.a, required this.b, required this.e, required this.dense})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Heun's 2(1) pair as a tableau.
final heun = RkTableau(name: 'heun21', order: 2, errorOrder: 1,
c: Float64List.fromList([0, 1]), a: [Float64List(0), Float64List.fromList([1])],
b: Float64List.fromList([0.5, 0.5]), e: Float64List.fromList([-0.5, 0.5, 0]), dense: const [[1.0, -0.5], [0.0, 0.5], [0.0, 0.0]]);
void f(double t, Float64List y, Float64List dy) => dy[0] = -y[0];
final s = ExplicitRkStepper(f, 0, Float64List.fromList([1]), 1, tableau: heun, rtol: 1e-6);
var n = 0;
while (s.step() && s.t < 1) {
n++;
}
print('${heun.name}: ${n + 1} steps, y(1) = ${s.y[0].toStringAsFixed(6)} (e⁻¹ = ${math.exp(-1).toStringAsFixed(6)})');
}heun21: 484 steps, y(1) = 0.367880 (e⁻¹ = 0.367879)
Properties
final String namefinal int errorOrderOrder of the propagated solution and of the embedded error estimate.
final List<double> cNodes (s), lower-triangular coupling rows (s rows, row i has i entries), weights (s), error weights (s + 1, the last multiplying the FSAL stage).
final List<double> bNodes (s), lower-triangular coupling rows (s rows, row i has i entries), weights (s), error weights (s + 1, the last multiplying the FSAL stage).
final List<double> eNodes (s), lower-triangular coupling rows (s rows, row i has i entries), weights (s), error weights (s + 1, the last multiplying the FSAL stage).
final List<List<double>> afinal List<List<double>> denseThe continuous extension: weight i at \theta \in [0, 1] is \sum_{k} \operatorname{dense}[i]{}[k] \theta^{k + 1} (s + 1 rows).
int get stagesExplicitRkStepper
final class ExplicitRkStepper extends OdeStepper
The adaptive explicit Runge–Kutta stepper (SciPy's RungeKutta._step_impl), for dormandPrince54 and tsitouras54. Buffers are allocated once; step allocates nothing.
Constructors
ExplicitRkStepper(this.f, double t0, Float64List y0, this.tBound, {this.tableau = dormandPrince54, double rtol = 1e-3, Object atol = 1e-6, double maxStep = double.infinity, double? firstStep})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = ExplicitRkStepper(f, 0, Float64List.fromList([1, 0]), 10, rtol: 1e-6, atol: 1e-9);
final h = <List<double>>[];
while (s.step()) {
h.add([s.t, s.stepSize]);
if (s.t >= 10) break;
}
print('Dormand–Prince: ${h.length} steps');
}Dormand–Prince: 52 steps
Properties
final OdeFunction ffinal double tBoundfinal double maxStepfinal double directionfinal RkTableau tableaufinal int nlate final double rtollate final Float64List atoldouble get tFloat64List get ydouble get tOlddouble get stepSizeFloat64List get currentDerivativeThe right-hand side at the current point (FSAL).
Methods
bool step()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = ExplicitRkStepper(f, 0, Float64List.fromList([1, 0]), 1, tableau: tsitouras54);
print('first step accepted: ${s.step()}, t = ${s.t.toStringAsFixed(4)}');
}first step accepted: true, t = 0.0010
void denseInto(double time, Float64List out)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = ExplicitRkStepper(f, 0, Float64List.fromList([1, 0]), 6, rtol: 1e-3);
s.step();
final out = Float64List(2);
s.denseInto(s.t * 0.3, out);
print('y(${(s.t * 0.3).toStringAsFixed(4)}) = ${out[0].toStringAsFixed(6)}');
}y(0.0003) = 1.000000
DenseSegment denseSegment()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = ExplicitRkStepper(f, 0, Float64List.fromList([1, 0]), 6, rtol: 1e-3);
s.step();
s.step();
final g = s.denseSegment();
print('the second step covers [${g.tMin.toStringAsFixed(4)}, ${g.tMax.toStringAsFixed(4)}]');
}the second step covers [0.0010, 0.0110]
RadauStepper
final class RadauStepper extends OdeStepper
Radau IIA (order 5) stepper (SciPy's Radau). jac analytic, else finite differences.
Constructors
RadauStepper(this.f, double t0, Float64List y0, this.tBound, {this.jac, double rtol = 1e-3, Object atol = 1e-6, this.maxStep = double.infinity, double? firstStep})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Robertson's stiff chemistry problem.
void f(double t, Float64List y, Float64List dy) {
dy[0] = -0.04 * y[0] + 1e4 * y[1] * y[2];
dy[1] = 0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] * y[1];
dy[2] = 3e7 * y[1] * y[1];
}
final s = RadauStepper(f, 0, Float64List.fromList([1, 0, 0]), 40, rtol: 1e-6, atol: 1e-10);
var steps = 0;
final pts = <List<double>>[];
while (s.step()) {
steps++;
pts.add([s.t, s.y[0]]);
if (s.t >= 40) break;
}
print('RadauStepper: $steps steps to t = 40, y = ${s.y.map((v) => v.toStringAsExponential(4)).toList()}');
}RadauStepper: 78 steps to t = 40, y = [7.1583e-1, 9.1855e-6, 2.8416e-1]
Properties
final OdeFunction ffinal OdeJacobianFunction? jacfinal double tBoundfinal double maxStepfinal double directionfinal int nlate final double rtollate final Float64List atollate final double newtonToldouble get tFloat64List get ydouble get tOlddouble get stepSizeMethods
bool step()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = RadauStepper(f, 0, Float64List.fromList([1, 0]), 6, rtol: 1e-6);
var n = 0;
while (s.step()) {
n++;
if (s.t >= 6) break;
}
print('$n steps; y(6) = ${s.y[0].toStringAsFixed(6)}, cos 6 = ${math.cos(6).toStringAsFixed(6)}');
}47 steps; y(6) = 0.960170, cos 6 = 0.960170
void denseInto(double time, Float64List out)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = RadauStepper(f, 0, Float64List.fromList([1, 0]), 3, rtol: 1e-6);
s.step();
s.step();
final mid = (s.tOld + s.t) / 2, out = Float64List(2);
s.denseInto(mid, out);
print('between ${s.tOld.toStringAsFixed(4)} and ${s.t.toStringAsFixed(4)}: y(${mid.toStringAsFixed(4)}) = ${out[0].toStringAsFixed(6)} (cos = ${math.cos(mid).toStringAsFixed(6)})');
}between 0.0109 and 0.1200: y(0.0654) = 0.997860 (cos = 0.997860)
DenseSegment denseSegment()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = RadauStepper(f, 0, Float64List.fromList([1, 0]), 6, rtol: 1e-6);
final segs = <DenseSegment>[];
while (s.step()) {
segs.add(s.denseSegment());
if (s.t >= 6) break;
}
final out = Float64List(2);
final pts = <List<double>>[];
for (final g in segs) {
for (var k = 0; k < 4; k++) {
final t = g.tMin + (g.tMax - g.tMin) * k / 4;
g.evaluate(t, out);
pts.add([t, out[0]]);
}
}
print('${segs.length} segments');
}47 segments
OdeMethod
enum OdeMethod
The adaptive methods solveIvp offers.
Values
radauRadau IIA order 5, stiff (L-stable; the most accurate stiff choice at tight tolerances).
OdeEvent
final class OdeEvent
An event function g(t, y); solveIvp finds its zeros.
Constructors
const OdeEvent(this.g, {this.terminal = false, this.maxCount = 1, this.direction = 0})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// A ball dropped from 10 m: stop when it hits the ground (y crosses 0 going down).
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -9.81;
}
final hit = OdeEvent((t, y) => y[0], terminal: true, direction: -1);
final sol = solveIvp(f, (0, 10), [10, 0], events: [hit], denseOutput: true);
final th = sol.tEvents[0].first;
print('lands at t = ${th.toStringAsFixed(6)} s (√(20/9.81) = ${math.sqrt(20 / 9.81).toStringAsFixed(6)})');
}lands at t = 1.427843 s (√(20/9.81) = 1.427843)
Properties
final double Function(double t, Float64List y) gfinal int maxCountfinal double direction0: only zeros where g goes from negative to positive; < 0: positive to negative; 0: both.
OdeSolution
final class OdeSolution
The result of solveIvp.
Properties
final List<double> tOutput times (every accepted step, or the requested ones) and the states there.
final List<Float64List> yfinal OdeInterpolant? solThe continuous solution over the whole interval, when denseOutput: true.
final List<List<Float64List>> yEventsfinal int nfevfinal int njevfinal int nlufinal String messagebool get successOdeInterpolant
final class OdeInterpolant
A piecewise continuous solution made of the steps' interpolants.
Constructors
OdeInterpolant(this.segments, this.n)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final s = createStepper(OdeMethod.rk45, f, 0, Float64List.fromList([1, 0]), 4);
final segs = <DenseSegment>[];
while (s.step()) {
segs.add(s.denseSegment());
if (s.t >= 4) break;
}
final y = OdeInterpolant(segs, 2);
print('${segs.length} segments; y(1) = ${y(1)[0].toStringAsFixed(4)}');
}8 segments; y(1) = 0.5403
Properties
final List<DenseSegment> segmentsfinal int ndouble get tMindouble get tMaxMethods
Float64List call(double t, [Float64List? out])y(t) into out (allocated when null). Times outside the range extrapolate the nearest segment.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
void f(double t, Float64List y, Float64List dy) {
dy[0] = y[1];
dy[1] = -y[0];
}
final sol = solveIvp(f, (0, 6), [1, 0], denseOutput: true, rtol: 1e-8);
final out = Float64List(2);
sol.sol!(2.0, out);
print('y(2) = (${out[0].toStringAsFixed(8)}, ${out[1].toStringAsFixed(8)})');
}y(2) = (-0.41614690, -0.90929689)
SymplecticMethod
enum SymplecticMethod
Values
velocityVerletKick-drift-kick with the acceleration cached between steps: order 2, one force evaluation per step.
leapfrogDrift-kick-drift (position Verlet): order 2, one force evaluation per step, no cached state.
yoshida4Yoshida's triple jump over velocity Verlet: order 4, three force evaluations per step.
yoshida6Yoshida's solution A, seven Verlet substeps: order 6, seven force evaluations per step.
SymplecticCompositionWeights
extension SymplecticCompositionWeights on SymplecticMethod
The composition weights of each method: the step fractions of its second-order substeps (velocity Verlet / leapfrog: [1]; Yoshida 4: the triple jump; Yoshida 6: solution A). Other symplectic splittings (accelerator drift–kick maps in riptide_accelerator_cpu) compose their own second-order step with the same weights.
Properties
List<double> get compositionWeightsSymplecticIntegrator
final class SymplecticIntegrator
A symplectic stepper over positions q and velocities v (length n each). step allocates nothing.
Constructors
SymplecticIntegrator(this.method, this.accel, this.n)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Kepler orbit: a = −q/|q|³.
void acc(Float64List q, Float64List a) {
final r2 = q[0] * q[0] + q[1] * q[1], r3 = r2 * math.sqrt(r2);
a[0] = -q[0] / r3;
a[1] = -q[1] / r3;
}
final series = <Map<String, Object>>[];
for (final m in SymplecticMethod.values) {
final s = SymplecticIntegrator(m, acc, 2);
final q = Float64List.fromList([1, 0]), v = Float64List.fromList([0, 1.2]);
final e = <List<double>>[];
for (var i = 0; i < 400; i++) {
s.step(q, v, 0.05);
e.add([i * 0.05, 0.5 * (v[0] * v[0] + v[1] * v[1]) - 1 / math.sqrt(q[0] * q[0] + q[1] * q[1])]);
}
series.add({'label': m.name, 'points': e});
print('${m.name.padRight(15)} energy after 400 steps ${e.last[1].toStringAsFixed(6)} (start −0.28)');
}
}velocityVerlet energy after 400 steps -0.279804 (start −0.28) leapfrog energy after 400 steps -0.279947 (start −0.28) yoshida4 energy after 400 steps -0.280001 (start −0.28) yoshida6 energy after 400 steps -0.280000 (start −0.28)
Properties
final SymplecticMethod methodfinal AccelerationFunction accelfinal int nMethods
void invalidate()Call after changing q outside step (the cached acceleration is stale).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Kepler orbit: a = −q/|q|³.
void acc(Float64List q, Float64List a) {
final r2 = q[0] * q[0] + q[1] * q[1], r3 = r2 * math.sqrt(r2);
a[0] = -q[0] / r3;
a[1] = -q[1] / r3;
}
final s = SymplecticIntegrator(SymplecticMethod.velocityVerlet, acc, 2);
final q = Float64List.fromList([1, 0]), v = Float64List.fromList([0, 1]);
s.step(q, v, 0.01);
q[0] = 2; // moved by hand: the cached acceleration is stale
s.invalidate();
s.step(q, v, 0.01);
print('q = ${q.map((x) => x.toStringAsFixed(6)).toList()}');
}q = [1.999888, 0.019999]
void step(Float64List q, Float64List v, double h)One step of size h; q and v are updated in place.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Kepler orbit: a = −q/|q|³.
void acc(Float64List q, Float64List a) {
final r2 = q[0] * q[0] + q[1] * q[1], r3 = r2 * math.sqrt(r2);
a[0] = -q[0] / r3;
a[1] = -q[1] / r3;
}
final s = SymplecticIntegrator(SymplecticMethod.yoshida4, acc, 2);
final q = Float64List.fromList([1, 0]), v = Float64List.fromList([0, 1]);
final pts = <List<double>>[];
for (var i = 0; i < 64; i++) {
pts.add([q[0], q[1]]);
s.step(q, v, 0.1);
}
print('circular orbit radius after 64 steps: ${math.sqrt(q[0] * q[0] + q[1] * q[1]).toStringAsFixed(8)}');
}circular orbit radius after 64 steps: 0.99999965
void integrate(Float64List q, Float64List v, double h, int steps)steps steps of size h.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Kepler orbit: a = −q/|q|³.
void acc(Float64List q, Float64List a) {
final r2 = q[0] * q[0] + q[1] * q[1], r3 = r2 * math.sqrt(r2);
a[0] = -q[0] / r3;
a[1] = -q[1] / r3;
}
final q = Float64List.fromList([1, 0]), v = Float64List.fromList([0, 1]);
SymplecticIntegrator(SymplecticMethod.leapfrog, acc, 2).integrate(q, v, 0.01, 628);
print('after one period: q = (${q[0].toStringAsFixed(5)}, ${q[1].toStringAsFixed(5)})');
}after one period: q = (0.99999, -0.00339)
OptimizeResult
final class OptimizeResult
The outcome of a minimisation or a multivariate root/least-squares solve (SciPy's OptimizeResult).
Constructors
OptimizeResult({required this.x, required this.fun, required this.nit, required this.nfev, required this.success, required this.message, this.njev = 0, this.grad, this.residual})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = OptimizeResult(x: Float64List.fromList([1, 2]), fun: 0.5, nit: 7, nfev: 21, success: true, message: 'converged');
print(r);
print('x ${r.x}, success ${r.success}');
}OptimizeResult(success: true, fun: 0.5, nit: 7, nfev: 21, message: converged, x: [1.0, 2.0]) x [1.0, 2.0], success true
Properties
final double funThe objective at x (for least squares, \tfrac{1}{2}\Vert r\Vert^{2}; for systems, \tfrac{1}{2}\Vert F\Vert^{2}).
final bool successfinal String messageMethods
String toString()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final fg = valueAndGradientForward((x) => x[0].square() + (x[1] - Dual.constant(1)).square());
print(minimizeBfgs(fg, Float64List.fromList([3, 3])));
}OptimizeResult(success: true, fun: 7.703719777548943e-32, nit: 3, nfev: 4, message: converged, x: [-1.6653345369377348e-16, 1.0000000000000002])
ScalarResult
final class ScalarResult
The outcome of a scalar root or scalar minimisation.
Constructors
const ScalarResult(this.x, this.fun, this.iterations, this.evaluations, this.converged, this.message)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
const r = ScalarResult(1.414, 0.0, 5, 6, true, 'converged');
print(r);
print('x = ${r.x}, iterations ${r.iterations}');
}ScalarResult(x: 1.414, fun: 0.0, iterations: 5, converged: true) x = 1.414, iterations 5
Properties
final double xfinal int iterationsfinal int evaluationsfinal bool convergedfinal String messageMethods
String toString()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print(brentq((x) => x * x - 2, 0, 2));
}ScalarResult(x: 1.4142135623731364, fun: 1.1723955140041653e-13, iterations: 8, converged: true)
OptimizeException
class OptimizeException implements Exception
Thrown when an input is invalid (bracket without a sign change, infeasible bounds...).
Constructors
OptimizeException(this.message)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
try {
brentq((x) => x * x + 1, -1, 1); // no sign change
} on OptimizeException catch (e) {
print('caught: ${e.message}');
} catch (e) {
print('caught ${e.runtimeType}: $e');
}
print(OptimizeException('custom'));
}caught: f(a) and f(b) must have different signs OptimizeException: custom
Properties
final String messageMethods
String toString()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print(OptimizeException('line search failed'));
}OptimizeException: line search failed
WolfeLineSearch
final class WolfeLineSearch
A line search along p from x: evaluates the objective and gradient at x + \alpha p into xTrial / gTrial.
Constructors
WolfeLineSearch(this.fg, int n)import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// f(x) = (x0 − 2)² + x1², searching from (0, 1) along the steepest descent direction.
double fg(Float64List x, Float64List g) {
g[0] = 2 * (x[0] - 2);
g[1] = 2 * x[1];
return (x[0] - 2) * (x[0] - 2) + x[1] * x[1];
}
final ls = WolfeLineSearch(fg, 2);
final x = Float64List.fromList([0, 1]), g = Float64List(2);
final f0 = fg(x, g);
final p = Float64List.fromList([-g[0], -g[1]]);
final alpha = ls.search(x, p, f0, g[0] * p[0] + g[1] * p[1]);
print('step length α = $alpha');
}step length α = 0.5
Properties
final ValueAndGradient fgfinal Float64List xTrialfinal Float64List gTrialdouble get phiStarMethods
double? search(Float64List x, Float64List p, double phi0, double derphi0, {double? oldPhi0, double c1 = 1e-4, double c2 = 0.9, double? amax, double? alpha1Guess, int maxiter = 20})Returns \alpha satisfying the strong Wolfe conditions, or null. On success xTrial / gTrial hold x + \alpha p and its gradient and phiStar its objective.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
double fg(Float64List x, Float64List g) {
g[0] = 4 * x[0] * x[0] * x[0];
return x[0] * x[0] * x[0] * x[0];
}
final ls = WolfeLineSearch(fg, 1);
final x = Float64List.fromList([1]), g = Float64List(1);
final f0 = fg(x, g);
final p = Float64List.fromList([-1]);
print('α = ${ls.search(x, p, f0, g[0] * p[0])}');
print('with c2 = 0.1 (strict): α = ${ls.search(x, p, f0, g[0] * p[0], c2: 0.1)}');
}α = 1.0 with c2 = 0.1 (strict): α = 1.0
Sobol
class Sobol
A Sobol low-discrepancy sequence in [0, 1)^dims. Unscrambled, it matches scipy.stats.qmc.Sobol(d, scramble=False) point for point (the first point is the origin). shift (one 30-bit word per dimension, from Sobol.randomShift) applies a digital shift.
Constructors
Sobol(this.dims, {Int32List? shift})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final s = Sobol(2);
final pts = s.take(256);
final rng = math.Random(1);
print('first points: ${[for (var i = 0; i < 4; i++) '(${pts[2 * i]}, ${pts[2 * i + 1]})']}');
}first points: [(0.0, 0.0), (0.5, 0.5), (0.75, 0.25), (0.25, 0.75)]
Static
static const int bits = 30static const int maxDims = 1024static Int32List randomShift(int dims, math.Random rng)A random digital shift for dims dimensions.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final shift = Sobol.randomShift(2, math.Random(9));
final s = Sobol(2, shift: shift);
final p = s.take(2);
print('shift $shift');
print('shifted first points: $p');
}shift [458359283, 1043999694] shifted first points: [0.42688034754246473, 0.9723004829138517, 0.9268803475424647, 0.47230048291385174]
Properties
final int dimsMethods
void nextInto(Float64List out)The next point into out (length dims).
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final s = Sobol(3);
final out = Float64List(3);
for (var i = 0; i < 4; i++) {
s.nextInto(out);
print(out);
}
}[0.0, 0.0, 0.0] [0.5, 0.5, 0.5] [0.75, 0.25, 0.25] [0.25, 0.75, 0.75]
Float64List take(int n)The next n points, n x dims row-major.
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final s = Sobol(1);
print(s.take(8));
print('next 8: ${s.take(8)}');
}[0.0, 0.5, 0.75, 0.25, 0.375, 0.875, 0.625, 0.125] next 8: [0.1875, 0.6875, 0.9375, 0.4375, 0.3125, 0.8125, 0.5625, 0.0625]
QuadResult
final class QuadResult
The outcome of an adaptive quadrature.
Constructors
const QuadResult(this.value, this.error, this.evaluations, {this.intervals = 1, this.status = 0})import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
const r = QuadResult(3.14159, 1e-9, 63);
print(r);
print('value ${r.value}, error ${r.error}, evaluations ${r.evaluations}, status ${r.status}');
}QuadResult(3.14159 ± 1e-9, 63 evaluations, status 0) value 3.14159, error 1e-9, evaluations 63, status 0
Properties
final int statusQUADPACK's ier: 0 converged; 1 subdivision limit; 2 round-off detected; 3 bad integrand behaviour; 4 extrapolation did not converge; 5 probably divergent; 6 invalid input.
bool get convergedMethods
String toString()import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print(quad((x) => 1 / (1 + x * x), -1e3, 1e3));
}QuadResult(3.139592654256459 ± 4.381015884524921e-11, 819 evaluations, status 0)