RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Numerical computing

Calculus and solvers

Automatic differentiation, ODE solvers (explicit, stiff, symplectic, batched), B-spline, NURBS and RBF interpolation, quadrature, root finding and optimisation.

import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray';
import 'package:riptide_numerics_calculus/autodiff.ray';
import 'package:riptide_numerics_calculus/interpolate.ray';
import 'package:riptide_numerics_calculus/linalg.ray';
import 'package:riptide_numerics_calculus/ode.ray';
import 'package:riptide_numerics_calculus/optimize.ray';
import 'package:riptide_numerics_calculus/quadrature.ray';
52 classes326 functions and methods280 of 593 documented283 runnable examplesWhat scipy.integrate, interpolate and optimize do

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).

LibraryContents
autodiff.rayForward mode (Dual, an extension type over Float64x2: no allocation) and reverse mode (tape)
ode.rayRK4, Dormand–Prince RK45, Tsit5 (dense output, events), BDF, Radau IIA, symplectic integrators, batched ensembles
interpolate.rayLinear, cubic, B-splines, NURBS, Akima, PCHIP, Catmull–Rom, bicubic/tricubic, RBF
quadrature.rayGauss–Legendre/Kronrod (adaptive), Romberg, tanh-sinh, Monte Carlo / Sobol
optimize.rayBisection, Brent, Newton/Halley, secant; Newton, BFGS, L-BFGS-B, CG, Nelder–Mead, LM, trust region
linalg.rayThe 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

derivativefunction
double derivative(Dual Function(Dual x) f, double x)

The derivative f'(x) of a scalar function written over Dual.

Example
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)}');
}
Output
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).

Example
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)');
}
Output
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.

Example
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');
}
Output
∇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.

Example
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]]]},
      ]})}');
}
Output
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.

Example
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]}]]');
}
Output
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).

Example
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])');
}
Output
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.

Example
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)})');
  }
}
Output
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).

Example
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)}');
}
Output
f = [6.0, 5.0]
row 0: [6.0, 3.0, 2.0]
row 1: [1.0, 4.0, 0.0]
vjpfunction
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.

Example
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])');
}
Output
f = [4.0, 6.0, 9.0]
(1, 1, 1)ᵀ J = [7.0, 8.0] (expected [7.0, 8.0])
findSpanfunction
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.

Example
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)}');
  }
}
Output
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).

Example
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];
          })(),
      ];
}
Output
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.

Example
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}');
}
Output
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.

Example
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}');
}
Output
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).

Example
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)}');
}
Output
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.

Example
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)}');
}
Output
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).

Example
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)}');
}
Output
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.

Example
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);
}
Output
λ chosen by generalised cross-validation: 2.894e-2
findIntervalfunction
int findInterval(Float64List x, double v)

Index i of the interval [xi, x[i + 1]) containing v, clamped to [0, x.length - 2].

Example
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)}');
  }
}
Output
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.

Example
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)');
}
Output
u(0.5) = 0.12500000000000003 (exact 1/8)
matVecfunction
void matVec(Float64List a, int m, int n, Float64List x, Float64List y)

y = A x for a row-major m \times n matrix.

Example
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');
}
Output
A x = [-2.0, -2.0]
dotfunction
double dot(Float64List a, Float64List b)
Example
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])));
}
Output
32.0
norm2function
double norm2(Float64List a)
Example
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]))}');
}
Output
5.0
no overflow: 1.414213562373095e+200
normInffunction
double normInf(Float64List a)
Example
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])));
}
Output
7.0
rmsScaledfunction
double rmsScaled(Float64List x, Float64List scale)

RMS norm of x / scale (SciPy's norm(x / scale)).

Example
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)}');
}
Output
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.

Example
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');
}
Output
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).

Example
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)}');
  }
}
Output
rtol 0.001: h0 = 1.468e-1
rtol 0.000001: h0 = 4.642e-2
rtol 1e-9: h0 = 1.468e-2
minStepAtfunction
double minStepAt(double t, double direction)

10 ulps of t in direction: the smallest step the adaptive methods take (SciPy's min_step).

Example
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)}');
  }
}
Output
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).

Example
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]}]]');
}
Output
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).

Example
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)}');
}
Output
stiff Van der Pol (μ = 5): 291 steps, y(15) = 1.4206
aosToSoafunction
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.

Example
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)}');
}
Output
SoA: [1.0, 2.0, 3.0, 10.0, 20.0, 30.0]
soaToAosfunction
Float64List soaToAos(List<double> soa, int n, int d)
Example
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)}');
}
Output
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.

Example
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()}');
}
Output
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.

Example
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');
}
Output
(x, v) = (1, 0) -> (dx, dv) = [0.0, -1.0]
lorenzRhsfunction
TensorRhs lorenzRhs({double sigma = 10, double rho = 28, double beta = 8 / 3})

The Lorenz system, d = 3.

Example
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');
}
Output
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}.

Example
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');
}
Output
(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.

Example
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)]}');
}
Output
x(3) = [0.1497, 0.0749, -0.1497]
lorenzBatchfunction
OdeFunction lorenzBatch(int n, {double sigma = 10, double rho = 28, double beta = 8 / 3})
Example
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()}');
}
Output
3636 steps; state at t = 25: [-1.493, -2.643, 11.948]
OdeFunction centralGravityBatch(int n, {double gm = 1, double softening = 1e-3})
Example
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)}');
}
Output
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.

Example
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)}');
}
Output
16 steps; y(2) = 0.0183159184, exact 0.0183156389
solveIvpfunction
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.

Example
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]]]}
      ]})}');
}
Output
y(π) = -1.00000000 (exact −1)
brentRootfunction
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.

Example
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)}');
}
Output
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).

Example
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()}');
}
Output
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).

Example
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()}');
}
Output
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).

Example
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])');
}
Output
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.

Example
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()}');
}
Output
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).

Example
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');
}
Output
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.

Example
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})');
}
Output
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).

Example
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');
}
Output
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.

Example
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)}');
}
Output
with b ≥ −0.5: a = 1.7596, b = -0.5000
solveNewtonfunction
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}.

Example
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');
}
Output
(1.17422174, 1.61901306) in 5 iterations
linprogfunction
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.

Example
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}');
}
Output
optimum at [1.0, 3.0], value 7.0
quadprogfunction
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).

Example
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}');
}
Output
x = [0.0, 2.0], f = -8.0
minimizeBfgsfunction
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.

Example
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)');
}
Output
minimum at (1.000000, 1.000000), exact (1, 1)
minimizeCgfunction
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').

Example
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');
}
Output
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.

Example
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');
}
Output
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.

Example
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');
}
Output
no derivatives: [1.00000, 1.00000], 219 evaluations
bisectfunction
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.

Example
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)}');
}
Output
√2 by bisection: 1.4142135624
brentqfunction
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.

Example
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}');
}
Output
root = 2.094551481542
f(root) is about 0: true
newtonfunction
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).

Example
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}');
}
Output
√2 ≈ 1.4142135623730951 in 5 iterations
without a derivative (secant): 1.414213562373095
secantfunction
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).

Example
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)}');
}
Output from the Raya VM
ln 3 ≈ 1.0986122886681096 (9 iterations), ln 3 = 1.0986122886681098
newtonADfunction
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).

Example
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)}');
}
Output
cube root of 2 = 1.259921049895
pow(2, 1/3)    = 1.259921049895
halleyADfunction
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).

Example
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}');
}
Output
∛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).

Example
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)}');
}
Output
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).

Example
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}');
}
Output
x = 1.30000000, evaluations 40
monteCarlofunction
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.

Example
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)}');
}
Output
π ≈ 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.

Example
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)}');
}
Output
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.

Example
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)}');
}
Output
Kronrod 21: 0.8820813907624215
error estimate: 8.82e-1
quadfunction
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.

Example
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)}');
}
Output
∫₀¹ 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.

Example
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)}');
}
Output
3-point nodes:   [-0.774597, 0.000000, 0.774597]
3-point weights: [0.555556, 0.888889, 0.555556]
∫ x⁴ = 0.400000000000
fixedQuadfunction
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).

Example
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)}');
}
Output
n = 2: 1.71789637800750
n = 3: 1.71828100437252
n = 5: 1.71828182845839
n = 8: 1.71828182845905
exact:  1.71828182845905
rombergfunction
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).

Example
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');
}
Output
∫₀¹ 4/(1 + x²) = 3.1415926536382437 (π = 3.141592653589793), 33 evaluations
tanhSinhfunction
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.

Example
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)}');
}
Output
∫₀¹ 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.

Example
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})');
}
Output from the Raya VM
3.1415926535897936 (π = 3.141592653589793)
quadBoxfunction
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.

Example
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)})');
}
Output
∬ e^(−x²−y²) over [−3, 3]² = 3.1414538564 (π·erf(3)² ≈ 3.1414538564)

Constants and variables

odeEpsconstant
const double odeEps = 2.220446049250313e-16

Machine epsilon for doubles.

const RkTableau dormandPrince54

Dormand–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).

tsitouras54variable
final RkTableau tsitouras54

Tsitouras 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).

TensorRhstypedef
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

extension type

Dual

extension type const Dual._(Float64x2 _p)

A dual number: value + deriv·\varepsilon.

Example
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}');
}
Output
f(3) = 15.0, f'(3) = 8.0

Constructors

Dualconstructor
Dual(double value, [double deriv = 0])

Value + deriv·\varepsilon.

Example
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}ε');
}
Output
value 2.0, deriv 3.0
Dual(5) has deriv 0.0
(2 + 3ε)(5) = 10.0 + 15.0ε
Dual.constantconstructor
Dual.constant(double value)

A constant (derivative 0).

Example
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}');
}
Output
f(4) = 23.0, f'(4) = 8.0
Dual.variableconstructor
Dual.variable(double value)

The independent variable at value (derivative 1).

Example
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)');
}
Output
x³ at 2 = 8.0, d/dx = 12.0 (3·2² = 12)

Static

atan2staticmethod
static Dual atan2(Dual y, Dual x)
Example
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)}');
}
Output
atan2(sin 1, cos 1) = 1.0000000000
d/dt = 1.0000000000
maxstaticmethod
static Dual max(Dual a, Dual b)
Example
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²)');
}
Output
max(x², 4x) at 3 = 12.0, slope 4.0 (from 4x)
max(x², 4x) at 5 = 25.0, slope 10.0 (from x²)
minstaticmethod
static Dual min(Dual a, Dual b)
Example
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}');
}
Output
min(eˣ, x + 2) at 1 = 2.718282, slope 2.718282
min(eˣ, x + 2) at 2 = 4.0, slope 1.0

Properties

valuegetter
double get value
derivgetter
double get deriv

Methods

addScalarmethod
Dual addScalar(double c)

This + c for a plain double.

Example
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}');
}
Output
x + 10 = 11.5, derivative still 1.0
scalemethod
Dual scale(double c)

This · c for a plain double (both lanes scaled: one instruction).

Example
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}');
}
Output
½x² at 2 = 2.0, derivative 2.0
chainmethod
Dual chain(double fv, double dfv)

Applies f with f(value) = fv and f'(value) = dfv: (f(a), f'(a) \cdot a').

Example
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)}');
}
Output
σ(2x) at 0.25 = 0.6224593312
d/dx         = 0.4700074244
sinmethod
Dual sin()
Example
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]]},
      ]})}');
}
Output
sin x at 0.5 = 0.4794255386
derivative     = 0.8775825619
exact          = 0.8775825619
cosmethod
Dual cos()
Example
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]]},
      ]})}');
}
Output
cos x at 0.5 = 0.8775825619
derivative     = -0.4794255386
exact          = -0.4794255386
tanmethod
Dual tan()
Example
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]]},
      ]})}');
}
Output
tan x at 0.5 = 0.5463024898
derivative     = 1.2984464104
exact          = 1.2984464104
expmethod
Dual exp()
Example
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]]},
      ]})}');
}
Output
exp x at 0.5 = 1.6487212707
derivative     = 1.6487212707
exact          = 1.6487212707
logmethod
Dual log()
Example
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]]},
      ]})}');
}
Output
log x at 0.5 = -0.6931471806
derivative     = 2.0000000000
exact          = 2.0000000000
sqrtmethod
Dual sqrt()
Example
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]]},
      ]})}');
}
Output
sqrt x at 0.5 = 0.7071067812
derivative     = 0.7071067812
exact          = 0.7071067812
powmethod
Dual pow(double k)
Example
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]]},
      ]})}');
}
Output
x^3 at 0.5 = 0.1250000000
derivative     = 0.7500000000
exact          = 0.7500000000
powDualmethod
Dual powDual(Dual o)

\mathrm{this}^{o} for a dual exponent: exp(o \cdot \log(this)).

Example
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)}');
}
Output
2² = 4.0000000000
d/dx xˣ at 2 = 6.7725887222
exact        = 6.7725887222
tanhmethod
Dual tanh()
Example
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]]},
      ]})}');
}
Output
tanh x at 0.5 = 0.4621171573
derivative     = 0.7864477330
exact          = 0.7864477330
atanmethod
Dual atan()
Example
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]]},
      ]})}');
}
Output
atan x at 0.5 = 0.4636476090
derivative     = 0.8000000000
exact          = 0.8000000000
asinmethod
Dual asin()
Example
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]]},
      ]})}');
}
Output
asin x at 0.5 = 0.5235987756
derivative     = 1.1547005384
exact          = 1.1547005384
acosmethod
Dual acos()
Example
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]]},
      ]})}');
}
Output
acos x at 0.5 = 1.0471975512
derivative     = -1.1547005384
exact          = -1.1547005384
absmethod
Dual abs()
Example
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}');
}
Output
|x| at −3: value 3.0, slope -1.0
|x| at  2: value 2.0, slope 1.0
squaremethod
Dual square()
Example
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]]},
      ]})}');
}
Output
x^2 at 0.5 = 0.2500000000
derivative     = 1.0000000000
exact          = 1.0000000000

Operators

operator +operator
Dual operator +(Dual o)
Example
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}');
}
Output
x + y = 8.0
d/dx (x + y) = 1: 1.0
operator -operator
Dual operator -(Dual o)
Example
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}');
}
Output
x - y = -2.0
d/dx (x − y) = 1: 1.0
operator -operator
Dual operator -()
Example
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}');
}
Output
−x² at 2 = -4.0, slope -4.0
operator *operator
Dual operator *(Dual o)
Example
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}');
}
Output
x * y = 15.0
d/dx (x·y) = y = 5: 5.0
operator /operator
Dual operator /(Dual o)
Example
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}');
}
Output
x / y = 0.6000000000000001
d/dx (x / y) = 1/y = 0.2: 0.2
operator <operator
bool operator <(Dual o)
Example
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}');
}
Output
(2 + 100ε) < (3 − 100ε): true
(2 + 100ε) < (2 + 0ε):   false
relu slope at 1.5: 1.0
operator >operator
bool operator >(Dual o)
Example
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}');
}
Output
(2 + 100ε) > (3 − 100ε): false
(2 + 100ε) > (2 + 0ε):   false
relu slope at 1.5: 1.0
operator <=operator
bool operator <=(Dual o)
Example
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}');
}
Output
(2 + 100ε) <= (3 − 100ε): true
(2 + 100ε) <= (2 + 0ε):   true
relu slope at 1.5: 1.0
operator >=operator
bool operator >=(Dual o)
Example
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}');
}
Output
(2 + 100ε) >= (3 − 100ε): false
(2 + 100ε) >= (2 + 0ε):   true
relu slope at 1.5: 1.0
final class HyperDual

A hyper-dual number: v + d1·\varepsilon_{1} + d2·\varepsilon_{2} + d12·\varepsilon_{1}\varepsilon_{2}.

Constructors

HyperDualconstructor
const HyperDual(this.v, [this.d1 = 0, this.d2 = 0, this.d12 = 0])
Example
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}');
}
Output
x³ at 2: value 8.0, f' 12.0, f' 12.0, f'' 12.0
const HyperDual.constant(double value)

A constant.

Example
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}');
}
Output
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).

Example
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)');
}
Output
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

vfield
final double v
d1field
final double d1
d2field
final double d2
d12field
final double d12

Methods

addScalarmethod
HyperDual addScalar(double c)
Example
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}');
}
Output
x² − 9 at 3: f = 0.0, f' = 6.0, f'' = 2.0
scalemethod
HyperDual scale(double c)
Example
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)}');
}
Output
3eˣ at 1: f = 8.15484549, f'' = 8.15484549
chainmethod
HyperDual chain(double f0, double f1, double f2)

f(this) given f(v) = f0, f'(v) = f1, f''(v) = f2.

Example
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)}');
}
Output
σ(1) = 0.7310585786
σ'(1) = 0.1966119332, σ''(1) = -0.0908577477
HyperDual reciprocal()
Example
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]]},
      ]})}');
}
Output
1/x at 0.5 = 2.0000000000
derivative     = -4.0000000000
exact          = -4.0000000000
second derivative at 0.5: 16.0000000000
sinmethod
HyperDual sin()
Example
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]]},
      ]})}');
}
Output
sin x at 0.5 = 0.4794255386
derivative     = 0.8775825619
exact          = 0.8775825619
second derivative at 0.5: -0.4794255386
cosmethod
HyperDual cos()
Example
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]]},
      ]})}');
}
Output
cos x at 0.5 = 0.8775825619
derivative     = -0.4794255386
exact          = -0.4794255386
second derivative at 0.5: -0.8775825619
expmethod
HyperDual exp()
Example
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]]},
      ]})}');
}
Output
exp x at 0.5 = 1.6487212707
derivative     = 1.6487212707
exact          = 1.6487212707
second derivative at 0.5: 1.6487212707
logmethod
HyperDual log()
Example
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]]},
      ]})}');
}
Output
log x at 0.5 = -0.6931471806
derivative     = 2.0000000000
exact          = 2.0000000000
second derivative at 0.5: -4.0000000000
sqrtmethod
HyperDual sqrt()
Example
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]]},
      ]})}');
}
Output
sqrt x at 0.5 = 0.7071067812
derivative     = 0.7071067812
exact          = 0.7071067812
second derivative at 0.5: -0.7071067812
powmethod
HyperDual pow(double k)
Example
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]]},
      ]})}');
}
Output
x^3 at 0.5 = 0.1250000000
derivative     = 0.7500000000
exact          = 0.7500000000
second derivative at 0.5: 3.0000000000
tanhmethod
HyperDual tanh()
Example
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]]},
      ]})}');
}
Output
tanh x at 0.5 = 0.4621171573
derivative     = 0.7864477330
exact          = 0.7864477330
second derivative at 0.5: -0.7268619814
atanmethod
HyperDual atan()
Example
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]]},
      ]})}');
}
Output
atan x at 0.5 = 0.4636476090
derivative     = 0.8000000000
exact          = 0.8000000000
second derivative at 0.5: -0.6400000000
squaremethod
HyperDual square()
Example
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]]},
      ]})}');
}
Output
x^2 at 0.5 = 0.2500000000
derivative     = 1.0000000000
exact          = 1.0000000000
second derivative at 0.5: 2.0000000000

Operators

operator +operator
HyperDual operator +(HyperDual o)
Example
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)}");
}
Output
f(1)   = 2.0000000000
f'(1)  = 3.0000000000
f''(1) = 2.0000000000
operator -operator
HyperDual operator -(HyperDual o)
Example
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)}");
}
Output
f(1)   = 0.0000000000
f'(1)  = 1.0000000000
f''(1) = 2.0000000000
operator -operator
HyperDual operator -()
Example
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}");
}
Output
−x³ at 2: f = -8.0, f' = -12.0, f'' = -12.0
operator *operator
HyperDual operator *(HyperDual o)
Example
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)}");
}
Output
f(1)   = 0.8414709848
f'(1)  = 1.3817732907
f''(1) = 0.2391336269
operator /operator
HyperDual operator /(HyperDual o)
Example
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)}");
}
Output
f(1)   = 0.8414709848
f'(1)  = -0.3011686789
f''(1) = -0.2391336269
class

Tape

final class Tape

A tape recording operations on Vars for reverse-mode differentiation.

Constructors

Tapeconstructor
Tape([int capacity = 256])
Example
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}');
}
Output
z = 6.90929743
∂z/∂x = 2.58385316 (y + cos x = 2.58385316)
∂z/∂y = 2.0
nodes recorded: 5

Static

currentstaticgetter
static Tape get current

The tape Var operations record onto (the last one begin was called on).

Properties

lengthgetter
int get length

Number of nodes recorded.

Methods

beginmethod
void begin()

Clears the recording (keeping the storage) and makes this the active tape.

Example
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}');
  }
}
Output
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
variablemethod
Var variable(double value)

A new independent variable (an input of the function).

Example
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)}');
}
Output
f = a²b = -4.5
∂f/∂a = -6.0, ∂f/∂b = 2.25
variablesmethod
VarVec variables(Float64List values)

A vector of independent variables.

Example
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');
}
Output
Σ xᵢ² = 30.0, gradient [2.0, 4.0, 6.0, 8.0]
constantmethod
Var constant(double value)

A constant (no edges; its adjoint is computed but not used).

Example
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');
}
Output
f = 10x + 10 at 3 = 40.0
∂f/∂x = 10.0
inputs are only the variables: [10.0]
valuemethod
double value(Var v)
Example
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)}');
}
Output
tape.value(y) = 1.4468890366
y.value       = 1.4468890366
adjointmethod
double adjoint(Var v)

The adjoint \frac{\partial out}{\partial v} after backward.

Example
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)})');
}
Output
∂f/∂u = -0.65364362 (cos 4)
∂f/∂x = -2.61457448 (2x cos x² = -2.61457448)
backwardmethod
void backward(Var out)

Seeds ∂out/∂out = 1 and propagates adjoints to every node.

Example
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)})');
  }
}
Output
(-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.

Example
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');
}
Output
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.

Example
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');
}
Output
∇(xyz) at (1, 2, 3) = [6.0, 3.0, 2.0]
addmethod
VarVec add(VarVec a, VarVec b)

Elementwise a + b.

Example
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)}');
}
Output
a + b = [11.0, 22.0, 33.0]
∂Σ/∂a = [1.0, 1.0, 1.0]
∂Σ/∂b = [1.0, 1.0, 1.0]
submethod
VarVec sub(VarVec a, VarVec b)

Elementwise a - b.

Example
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)}');
}
Output
a − b = [-9.0, -18.0, -27.0]
∂Σ/∂a = [1.0, 1.0, 1.0]
∂Σ/∂b = [-1.0, -1.0, -1.0]
mulmethod
VarVec mul(VarVec a, VarVec b)

Elementwise a \cdot b.

Example
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)}');
}
Output
a · b = [10.0, 40.0, 90.0]
∂Σ/∂a = [10.0, 20.0, 30.0]
∂Σ/∂b = [1.0, 2.0, 3.0]
scalemethod
VarVec scale(VarVec a, double c)

a \cdot c for a constant c.

Example
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');
}
Output
2.5·v = [2.5, 5.0, 7.5]
gradient of Σ 2.5vᵢ = [2.5, 2.5, 2.5]
sinmethod
VarVec sin(VarVec a)
Example
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]]]},
      ]})}');
}
Output
sin(0.85) = 0.75128041, adjoint 0.65998315, exact 0.65998315
cosmethod
VarVec cos(VarVec a)
Example
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]]]},
      ]})}');
}
Output
cos(0.85) = 0.65998315, adjoint -0.75128041, exact -0.75128041
expmethod
VarVec exp(VarVec a)
Example
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]]]},
      ]})}');
}
Output
exp(0.85) = 2.33964685, adjoint 2.33964685, exact 2.33964685
logmethod
VarVec log(VarVec a)
Example
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]]]},
      ]})}');
}
Output
log(0.85) = -0.16251893, adjoint 1.17647059, exact 1.17647059
tanhmethod
VarVec tanh(VarVec a)
Example
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]]]},
      ]})}');
}
Output
tanh(0.85) = 0.69106947, adjoint 0.52242299, exact 0.52242299
squaremethod
VarVec square(VarVec a)
Example
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]]]},
      ]})}');
}
Output
square(0.85) = 0.72250000, adjoint 1.70000000, exact 1.70000000
summethod
Var sum(VarVec a)

\sum a_{i} (one node, n edges).

Example
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');
}
Output
mean of squares = 7.5
gradient = [0.5, -1.0, 1.5, -2.0]
dotmethod
Var dot(VarVec a, VarVec b)

\sum a_{i}b_{i} (one node, 2n edges).

Example
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)');
}
Output
a·b = 32.0
∂/∂a = [4.0, 5.0, 6.0] (= b), ∂/∂b = [1.0, 2.0, 3.0] (= a)
matVecmethod
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).

Example
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');
}
Output
Ax = [0.0, 0.5, 1.0]
loss = 4.25, gradient = [-21.0, -28.0]
valuesmethod
Float64List values(VarVec v)

The values of v into a new list.

Example
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))}');
}
Output
exp(v) = [1.0, 2.718281828459045, 7.38905609893065]
extension type

Var

extension type const Var._(int _i)

A recorded scalar on the Tape.current tape (an index into it; nothing is allocated).

Static

atan2staticmethod
static Var atan2(Var y, Var x)
Example
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)}');
}
Output
atan2(1, 1) = 0.7853981634 (π/4)
∂/∂y = 0.5, ∂/∂x = -0.5

Properties

indexgetter
int get index

Index of the node on its tape.

valuegetter
double get value

Methods

addScalarmethod
Var addScalar(double c)
Example
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)}');
}
Output
x² − 4 at 2 = 0.0, slope 4.0
scalemethod
Var scale(double c)
Example
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)}');
}
Output
−x/2 at 3 = -1.5, slope -0.5
sinmethod
Var sin()
Example
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]]},
      ]})}');
}
Output
sin at 0.5 = 0.4794255386, slope 0.8775825619, exact slope 0.8775825619
cosmethod
Var cos()
Example
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]]},
      ]})}');
}
Output
cos at 0.5 = 0.8775825619, slope -0.4794255386, exact slope -0.4794255386
tanmethod
Var tan()
Example
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]]},
      ]})}');
}
Output
tan at 0.5 = 0.5463024898, slope 1.2984464104, exact slope 1.2984464104
expmethod
Var exp()
Example
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]]},
      ]})}');
}
Output
exp at 0.5 = 1.6487212707, slope 1.6487212707, exact slope 1.6487212707
logmethod
Var log()
Example
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]]},
      ]})}');
}
Output
log at 0.5 = -0.6931471806, slope 2.0000000000, exact slope 2.0000000000
sqrtmethod
Var sqrt()
Example
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]]},
      ]})}');
}
Output
sqrt at 0.5 = 0.7071067812, slope 0.7071067812, exact slope 0.7071067812
powmethod
Var pow(double k)
Example
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]]},
      ]})}');
}
Output
pow(2.5) at 0.5 = 0.1767766953, slope 0.8838834765, exact slope 0.8838834765
tanhmethod
Var tanh()
Example
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]]},
      ]})}');
}
Output
tanh at 0.5 = 0.4621171573, slope 0.7864477330, exact slope 0.7864477330
atanmethod
Var atan()
Example
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]]},
      ]})}');
}
Output
atan at 0.5 = 0.4636476090, slope 0.8000000000, exact slope 0.8000000000
absmethod
Var abs()
Example
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]]},
      ]})}');
}
Output
abs at 0.5 = 0.5000000000, slope 1.0000000000, exact slope 1.0000000000
squaremethod
Var square()
Example
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]]},
      ]})}');
}
Output
square at 0.5 = 0.2500000000, slope 1.0000000000, exact slope 1.0000000000

Operators

operator +operator
Var operator +(Var o)
Example
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)');
}
Output
x + y = 7.0
∂f/∂x = 1.0 (1), ∂f/∂y = 1.0 (1)
operator -operator
Var operator -(Var o)
Example
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)');
}
Output
x - y = -3.0
∂f/∂x = 1.0 (1), ∂f/∂y = -1.0 (−1)
operator *operator
Var operator *(Var o)
Example
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)');
}
Output
x * y = 10.0
∂f/∂x = 5.0 (y = 5), ∂f/∂y = 2.0 (x = 2)
operator /operator
Var operator /(Var o)
Example
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)');
}
Output
x / y = 0.4
∂f/∂x = 0.2 (1/y = 0.2), ∂f/∂y = -0.08000000000000002 (−x/y² = −0.08)
operator -operator
Var operator -()
Example
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)}');
}
Output
−√x at 4 = -2.0, slope -0.25
class

VarVec

final class VarVec

A contiguous run of recorded scalars (the reverse-mode view of a float64 vector).

Properties

startfield
final int start
lengthfield
final int length

Operators

operator []operator
Var operator [](int k)
Example
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])}');
}
Output
‖(3, 4)‖ = 5.0
∂/∂v[0] = 0.6000000000000001, ∂/∂v[1] = 0.8
class

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

BSplineconstructor
BSpline(this.t, this.c, this.k, {this.dim = 1})
Example
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(); })()];
}
Output
degree 3, 6 control values, domain [0.0, 3.0]
s(1.5) = 1.03125

Static

designMatrixstaticmethod
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).

Example
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);
  }
}
Output
[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

tfield
final Float64List t
cfield
final Float64List c
kfield
final int k
dimfield
final int dim
ngetter
int get n

The number of coefficients.

lowergetter
double get lower

The base interval [t[k], t[n]].

uppergetter
double get upper

Methods

callmethod
double call(double v, [int nu = 0])

The value (or nuth derivative) of a scalar spline at v.

Example
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)}');
}
Output
s(1) = 1.833333333333333
s'(1) = -0.5
s''(1) = -7.0
evalIntomethod
void evalInto(double v, Float64List out, [int nu = 0])

The value (or nuth derivative) at v written into out (length dim).

Example
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');
}
Output
point at 1.5: [-0.75, 0.75]
tangent at 1.5: [-1.0, -1.0]
evalAllmethod
Float64List evalAll(Float64List v, [int nu = 0])

Evaluates a scalar spline at every point of v.

Example
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)}');
}
Output
[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]).

Example
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)}');
}
Output
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).

Example
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)}');
}
Output
antiderivative degree 4, a(0) = 0.0
a'(2) = 0.41666666666666674, s(2) = 0.41666666666666674
integratemethod
double integrate(double a, double b)

\int_{a}^{b} s for a scalar spline.

Example
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}');
}
Output
∫₀³ 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).

Example
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)}');
}
Output
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
toPPolymethod
PPoly toPPoly()

Converts to piecewise polynomial form over the distinct knots of the base interval.

Example
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)}');
}
Output
breakpoints [0.0, 1.0, 2.0, 3.0]
pieces of degree 3; p(1.5) = 1.0312499999999996, s(1.5) = 1.03125
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

CatmullRomSplineconstructor
CatmullRomSpline(this.points, {required this.dim, this.alpha = 0.5, this.closed = false})
Example
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}');
}
Output
open: 81 samples, closed: 101

Properties

pointsfield
final Float64List points
dimfield
final int dim
countfield
final int count
alphafield
final double alpha

0 uniform, 0.5 centripetal, 1 chordal.

closedfield
final bool closed
segmentsgetter
int get segments

Methods

pointIntomethod
void pointInto(double s, Float64List out)

The point at parameter s (in [0, segments]) into out.

Example
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)})');
  }
}
Output
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)
pointmethod
Float64List point(double s)
Example
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');
}
Output
uniform, centripetal and chordal parametrisations
class GridInterpolator

Tensor-product spline interpolation of values on the grid axes (values row-major, last axis fastest).

Constructors

GridInterpolatorconstructor
GridInterpolator(List<Float64List> axes, Float64List values, {this.degree = 3, this.outside = GridOutside.nan})
Example
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])}');
}
Output
g(1.5, 0.5) = 0.87656, exact 0.87538
outside: NaN

Properties

axesfield
final List<Float64List> axes
dimsfield
final int dims
degreefield
final int degree
outsidefield
final GridOutside outside

Methods

callmethod
double call(List<double> point, {List<int>? derivs})

The value at point (length dims); derivs gives the derivative order along each axis (default none).

Example
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)');
}
Output
f(1.5, 2) = 5.25
∂f/∂x = 4.999999999999999 (exact 2x + y = 5)
∂f/∂y = 1.5 (exact x = 1.5)
enum GridOutside

Out-of-range behaviour of GridInterpolator.

Values

nanvalue
nan

NaN (scipy's RegularGridInterpolator with bounds_error=False, fill_value=nan).

extrapolate

Continue the end polynomial pieces.

errorvalue
error

Throw a RangeError.

class NurbsCurve

A NURBS curve of degree in dim dimensions: knots, control points (n x dim, row-major) and weights.

Constructors

NurbsCurveconstructor
NurbsCurve(this.degree, this.knots, this.points, this.weights, {required this.dim})
Example
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])}');
}
Output
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).

Example
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');
}
Output
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).

Example
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)})');
}
Output
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.

Example
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)})');
}
Output
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.

Example
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)})');
  }
}
Output
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

degreefield
final int degree
dimfield
final int dim
knotsfield
final Float64List knots
pointsfield
final Float64List points
weightsfield
final Float64List weights
lowergetter
double get lower
uppergetter
double get upper

Methods

pointIntomethod
void pointInto(double u, Float64List out)

The point at parameter u into out (length dim).

Example
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');
}
Output
point at 1/8 of the circle: [0.7071067811865475, 0.7071067811865475]
pointmethod
Float64List point(double u)
Example
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)}');
}
Output
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.

Example
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)');
}
Output
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).

Example
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}');
}
Output
9 -> 10 control points
same point: true
lengthmethod
double length([double? a, double? b])

Arc length over [a, b] (default the whole curve): 8-point Gauss–Legendre per knot span, 4 subdivisions.

Example
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)}');
}
Output
full: 6.283185307179587
u in [0, 0.25]: 1.570796326794897
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

NurbsSurfaceconstructor
NurbsSurface(this.p, this.q, this.uKnots, this.vKnots, this.points, this.weights, {required this.nu, required this.nv, this.dim = 3})
Example
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)}');
}
Output
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).

Example
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])}');
}
Output
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.

Example
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)}');
  }
}
Output
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

pfield
final int p
qfield
final int q
nufield
final int nu
nvfield
final int nv
dimfield
final int dim
uKnotsfield
final Float64List uKnots
vKnotsfield
final Float64List vKnots
pointsfield
final Float64List points
weightsfield
final Float64List weights

Methods

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].

Example
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()}');
}
Output
S    = [0.8138, 0.5811, 1.5000]
S_v  = [0.0000, 0.0000, 3.0000]
S_u  = [-3.8250, 5.3568, 0.0000]
pointmethod
Float64List point(double u, double v)

The point S(u, v).

Example
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));
}
Output
[1.0, 0.0, 0.0]
[-1.0, 0.0, 1.0]
normalmethod
Float64List normal(double u, double v)

The unit normal Su \times Sv (3-D surfaces).

Example
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}');
}
Output
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.

Example
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}');
}
Output
v knots [0.0, 0.0, 1.0, 1.0] -> [0.0, 0.0, 0.5, 1.0, 1.0]
same point: true
enum Extrapolate

How a 1-D interpolant evaluates outside [x0, xn].

Values

extendvalue
extend

Continue the first/last polynomial piece (SciPy's extrapolate=True).

nanvalue
nan

Return NaN (SciPy's extrapolate=False).

periodic

Wrap the argument into the base interval (SciPy's extrapolate='periodic').

class

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

PPolyconstructor
PPoly(this.x, this.c, {this.extrapolate = Extrapolate.extend})
Example
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)}');
}
Output
degree 3, p(0.5) = -0.375, p(1.5) = 1.5

Properties

xfield
final Float64List x

Breakpoints (strictly increasing).

cfield
final List<Float64List> c

Coefficients, ci for power k - m on interval i.

kfield
final int k
final Extrapolate extrapolate
lowergetter
double get lower
uppergetter
double get upper

Methods

callmethod
double call(double v, [int nu = 0])

The nuth derivative at v.

Example
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)}');
}
Output
p(1.5) = 1.5, p'(1.5) = 3.5
extrapolated p(2.5) = 3.0
evalAllmethod
Float64List evalAll(Float64List v, [int nu = 0])

Evaluates at every point of v into a new list.

Example
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])));
}
Output
[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.

Example
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)}');
}
Output
degree 2; d(0.5) = -0.25
PPoly antiderivative()

The antiderivative that is 0 at x[0] and continuous, degree k + 1.

Example
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)}');
}
Output
degree 4; ∫₀² p = 1.25
integratemethod
double integrate(double a, double b)

\int_{a}^{b} p (with the same extrapolation rule; periodic integrates whole periods exactly).

Example
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)}');
}
Output
∫₀² p = 1.25
∫₂⁰ p = -1.25
solvemethod
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.

Example
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)}');
}
Output
roots of p: [0.0, 1.0]
where p = 0.2: [1.0888579869569162]
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})
Example
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)}');
}
Output
h(0.5) = 0.5, h'(1) = 0.0
sealed class SplineBoundary

A boundary condition of a CubicSpline.

Constructors

SplineBoundaryconstructor
const SplineBoundary()
Example
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)}');
  }
}
Output
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

notAKnotconstant
static const notAKnot = _NotAKnot()

The first and second piece are the same cubic (the third derivative is continuous at x[1]); SciPy's default.

naturalconstant
static const natural = SecondDerivative(0)

Second derivative zero at the end.

clampedconstant
static const clamped = FirstDerivative(0)

First derivative zero at the end.

periodicconstant
static const periodic = _Periodic()

Periodic (y[0] must equal y[n - 1]); set on both ends.

final class FirstDerivative extends SplineBoundary

A prescribed first derivative at the end.

Constructors

FirstDerivativeconstructor
const FirstDerivative(this.value)
Example
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)}');
}
Output
s'(0) = 1.0, s'(6) = 0.960170
error at 2.5: 1.89e-3

Properties

valuefield
final double value
final class SecondDerivative extends SplineBoundary

A prescribed second derivative at the end.

Constructors

SecondDerivativeconstructor
const SecondDerivative(this.value)
Example
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)}');
}
Output from the Raya VM
natural: s''(0) = 4.440892098500626e-16, s''(6) = -2.220446049250313e-16

Properties

valuefield
final double value
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).

Example
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]]]},
      ]})}');
}
Output
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})
Example
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)}');
}
Output
not-a-knot s(2.5) = 0.598744
natural    s(2.5) = 0.596223
sin 2.5          = 0.598472
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})
Example
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)}');
}
Output
pchip stays in [0, 1]: true
cubic spline overshoots: min -0.1303
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})
Example
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)}');
}
Output
akima(2.5) = 0.5000, makima(2.5) = 0.5000
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})
Example
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)}');
  }
}
Output
clamp       f(4) = 1.0
extrapolate f(4) = 0.5
nan         f(4) = NaN

Properties

xfield
final Float64List x
yfield
final Float64List y
outsidefield
final LinearOutside outside

Methods

callmethod
double call(double v)
Example
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)}');
}
Output
f(0.5) = 1.0, f(2) = 1.5, f(4) = 0.5
enum LinearOutside

Out-of-range behaviour of LinearInterpolator.

Values

clampvalue
clamp
extrapolate
nanvalue
nan
errorvalue
error
enum RbfKernel

RBF kernels \varphi(r), r = \varepsilon\Vert x - y\Vert (SciPy's names and signs).

Values

linearvalue
linear(0, true)
thinPlateSpline(1, true)
cubicvalue
cubic(1, true)
quinticvalue
quintic(2, true)
multiquadric(0, false)
inverseMultiquadric(-1, false)
inverseQuadratic(-1, false)
gaussian(-1, false)

Constructors

RbfKernelconstructor
const RbfKernel(this.minDegree, this.scaleInvariant)
Example
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}');
  }
}
Output
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 minDegree

The lowest polynomial degree that keeps the system solvable (-1: none needed).

final bool scaleInvariant

Whether \varepsilon has no effect (it may then be left at 1).

Methods

phimethod
double phi(double r)
Example
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)}');
  }
}
Output
thinPlateSpline: φ(1) = 0.0, φ(2) = 2.772589
cubic: φ(1) = 1.0, φ(2) = 8.000000
gaussian: φ(1) = 0.36787944117144233, φ(2) = 0.018316
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

RbfInterpolatorconstructor
RbfInterpolator(this.centers, Float64List values, {required this.dim, this.kernel = RbfKernel.thinPlateSpline, double? epsilon, this.smoothing = 0, int? degree, this.outputs = 1})
Example
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)');
}
Output
r(0.5, 0.5) = 0.2654 (exact 0.25)

Properties

centersfield
final Float64List centers
dimfield
final int dim
nfield
final int n
degreefield
final int degree
outputsfield
final int outputs
kernelfield
final RbfKernel kernel
epsilonfield
final double epsilon
final double smoothing

Methods

evalIntomethod
void evalInto(Float64List x, Float64List out)

The interpolant at x (length dim) into out (length outputs).

Example
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)');
}
Output
r(0.2, −0.4) = -0.0882 (exact −0.08)
callmethod
double call(List<double> x)

The (first output of the) interpolant at x.

Example
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)}');
}
Output
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)
Example
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}');
  }
}
Output
caught: zero pivot in column 1

Properties

messagefield
final String message

Methods

toStringmethod
String toString()
Example
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'));
}
Output
SingularMatrixException: zero pivot in column 1
class

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

DenseLuconstructor
DenseLu(Float64List a, this.n, {bool inPlace = false})

Factors a (n \times n, row-major). a is copied unless inPlace.

Example
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()}');
}
Output
x = [3.000000, 4.000000, -5.000000]

Properties

nfield
final int n
lufield
final Float64List lu
pivfield
final Int32List piv
signfield
int sign

+1 or -1: the sign of the row permutation (for the determinant).

double get determinant

Methods

void solveInPlace(Float64List b)

Solves A x = b in place in b.

Example
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()}');
}
Output
first column of A⁻¹: [0.625000, -0.500000, -0.125000]
solvemethod
Float64List solve(Float64List b)

A new vector x with A x = b.

Example
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());
  }
}
Output
[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.

Example
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)}');
  }
}
Output
eps 1.0: rcond ≈ 1.333e-1
eps 0.0001: rcond ≈ 2.500e-5
eps 1e-10: rcond ≈ 2.500e-11
final class DenseCholesky

Cholesky factorisation A = L L^{T} of a symmetric positive-definite row-major matrix (lower triangle used).

Constructors

DenseCholeskyconstructor
DenseCholesky(Float64List a, this.n)
Example
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');
}
Output
x = [0.5, 0.0]

Properties

nfield
final int n
lfield
final Float64List l

Methods

void solveInPlace(Float64List b)
Example
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');
}
Output
x = [1.5, 2.000000000000001, 1.5000000000000002]
class

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

DenseQrconstructor
DenseQr(Float64List a, this.m, this.n)
Example
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)}');
}
Output
intercept 0.9700, slope 2.0200

Properties

mfield
final int m
nfield
final int n
qrfield
final Float64List qr
taufield
final Float64List tau

Methods

applyQtmethod
void applyQt(Float64List b)

Applies Q^{T} to b (length m) in place.

Example
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)}');
}
Output
Qᵀy = [-8.0000, -4.5169, 0.1247, 0.0494]
residual norm = 0.1342
solvemethod
Float64List solve(Float64List b)

The least-squares solution x (length n) of A x \approx b.

Example
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));
}
Output
[0.9699999999999989, 2.02]
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

BdfStepperconstructor
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})
Example
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()}');
}
Output
BdfStepper: 144 steps to t = 40, y = [7.1583e-1, 9.1856e-6, 2.8416e-1]

Properties

ffield
final OdeFunction f
jacfield
final OdeJacobianFunction? jac
tBoundfield
final double tBound
maxStepfield
final double maxStep
final double direction
nfield
final int n
rtolfield
late final double rtol
atolfield
late final Float64List atol
late final double newtonTol
orderfield
int order
tgetter
double get t
ygetter
Float64List get y
tOldgetter
double get tOld
stepSizegetter
double get stepSize

Methods

stepmethod
bool step()
Example
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)}');
}
Output
64 steps; y(6) = 0.960152, cos 6 = 0.960170
denseIntomethod
void denseInto(double time, Float64List out)
Example
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)})');
}
Output
between 0.0001 and 0.0002: y(0.0002) = 1.000000 (cos = 1.000000)
DenseSegment denseSegment()
Example
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');
}
Output
64 segments
enum OdeStatus

Why a stepper stopped.

Values

runningvalue
running
finished
failedvalue
failed
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

tgetter
double get t

The current time and state.

ygetter
Float64List get y
tOldgetter
double get tOld

The start of the last accepted step.

stepSizegetter
double get stepSize

The step-size estimate for the next step (absolute).

ngetter
int get n
statusfield
OdeStatus status
messagefield
String? message
nfevfield
int nfev
njevfield
int njev
nlufield
int nlu

Methods

stepmethod
bool step()

Advances one accepted step (or to the bound). Returns false on failure (message says why).

Example
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)}');
}
Output
tsit5: 36 steps, last step size 0.2876
denseIntomethod
void denseInto(double time, Float64List out)

The last step's interpolant at time (in tOld, t) into out.

Example
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)})');
}
Output
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).

Example
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)}]');
}
Output
segment [0.0, 0.0010]
abstract class DenseSegment

One step's continuous extension.

Properties

tMingetter
double get tMin
tMaxgetter
double get tMax

Methods

evaluatemethod
void evaluate(double t, Float64List out)
Example
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');
}
Output
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)
Example
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()}');
}
Output
J ≈ [0.000000, 1.000000, -1.000000, -0.000000]

Properties

ffield
final OdeFunction f
nfield
final int n
atolfield
final Float64List atol
nfevfield
int nfev

Methods

callmethod
void call(double t, Float64List y, Float64List fy, Float64List jac)
Example
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)}');
  }
}
Output
d(y²)/dy at 1.0 ≈ 2.000000
d(y²)/dy at 2.0 ≈ 4.000000
d(y²)/dy at 3.0 ≈ 6.000000
enum EnsembleMethod

Values

rk4value
rk4

Classic RK4.

dopri5value
dopri5

Dormand–Prince 5(4) at a fixed step, with a per-system error estimate.

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})
Example
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)]}');
}
Output
x(3) = [-0.9900, 0.9602, -0.9111, 0.8438]
cos(3ω) = [-0.9900, 0.9602, -0.9111, 0.8439]

Properties

ffield
final OdeFunction f
nfield
final int n
dfield
final int d
methodfield
final EnsembleMethod method
final Float64List errorEstimate

For EnsembleMethod.dopri5: after each step, \max_{k} |local error| of each system.

nfevgetter
int get nfev

Methods

stepmethod
void step(double t, Float64List y, double h)

Advances y (length n \cdot d) from t by h.

Example
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()}');
}
Output
after one dopri5 step: [0.995004, 0.980067, 0.955336, 0.921060, -0.099833, -0.397339, -0.886561, -1.557675]
integratemethod
double integrate(double t0, Float64List y, double h, int steps)

steps steps of size h from t0. Returns the final time.

Example
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)]}');
}
Output
t = 3.0: x = [-0.98999, 0.96017, -0.91113, 0.84385]
final class Rk4Stepper

Classic fourth-order Runge–Kutta with a fixed step. step allocates nothing.

Constructors

Rk4Stepperconstructor
Rk4Stepper(this.f, this.n)
Example
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)})');
}
Output
after 63 steps of 0.1: (0.999858, -0.016809)

Properties

ffield
final OdeFunction f
nfield
final int n
nfevfield
int nfev

Methods

stepmethod
void step(double t, Float64List y, double h)

Advances y in place from t by h.

Example
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)}');
  }
}
Output
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
integratemethod
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.

Example
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)}');
}
Output
t = 6.28: y = 0.99999493
final class RkTableau

A Butcher tableau of an explicit embedded pair with FSAL (the last stage is f at the new point).

Constructors

RkTableauconstructor
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})
Example
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)})');
}
Output
heun21: 484 steps, y(1) = 0.367880 (e⁻¹ = 0.367879)

Properties

namefield
final String name
orderfield
final int order

Order of the propagated solution and of the embedded error estimate.

final int errorOrder

Order of the propagated solution and of the embedded error estimate.

cfield
final List<double> c

Nodes (s), lower-triangular coupling rows (s rows, row i has i entries), weights (s), error weights (s + 1, the last multiplying the FSAL stage).

bfield
final List<double> b

Nodes (s), lower-triangular coupling rows (s rows, row i has i entries), weights (s), error weights (s + 1, the last multiplying the FSAL stage).

efield
final List<double> e

Nodes (s), lower-triangular coupling rows (s rows, row i has i entries), weights (s), error weights (s + 1, the last multiplying the FSAL stage).

afield
final List<List<double>> a
densefield
final List<List<double>> dense

The continuous extension: weight i at \theta \in [0, 1] is \sum_{k} \operatorname{dense}[i]{}[k] \theta^{k + 1} (s + 1 rows).

stagesgetter
int get stages
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})
Example
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');
}
Output
Dormand–Prince: 52 steps

Properties

ffield
final OdeFunction f
tBoundfield
final double tBound
maxStepfield
final double maxStep
final double direction
tableaufield
final RkTableau tableau
nfield
final int n
rtolfield
late final double rtol
atolfield
late final Float64List atol
tgetter
double get t
ygetter
Float64List get y
tOldgetter
double get tOld
stepSizegetter
double get stepSize
Float64List get currentDerivative

The right-hand side at the current point (FSAL).

Methods

stepmethod
bool step()
Example
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)}');
}
Output
first step accepted: true, t = 0.0010
denseIntomethod
void denseInto(double time, Float64List out)
Example
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)}');
}
Output
y(0.0003) = 1.000000
DenseSegment denseSegment()
Example
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)}]');
}
Output
the second step covers [0.0010, 0.0110]
final class RadauStepper extends OdeStepper

Radau IIA (order 5) stepper (SciPy's Radau). jac analytic, else finite differences.

Constructors

RadauStepperconstructor
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})
Example
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()}');
}
Output
RadauStepper: 78 steps to t = 40, y = [7.1583e-1, 9.1855e-6, 2.8416e-1]

Properties

ffield
final OdeFunction f
jacfield
final OdeJacobianFunction? jac
tBoundfield
final double tBound
maxStepfield
final double maxStep
final double direction
nfield
final int n
rtolfield
late final double rtol
atolfield
late final Float64List atol
late final double newtonTol
tgetter
double get t
ygetter
Float64List get y
tOldgetter
double get tOld
stepSizegetter
double get stepSize

Methods

stepmethod
bool step()
Example
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)}');
}
Output
47 steps; y(6) = 0.960170, cos 6 = 0.960170
denseIntomethod
void denseInto(double time, Float64List out)
Example
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)})');
}
Output
between 0.0109 and 0.1200: y(0.0654) = 0.997860 (cos = 0.997860)
DenseSegment denseSegment()
Example
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');
}
Output
47 segments
enum OdeMethod

The adaptive methods solveIvp offers.

Values

rk45value
rk45

Dormand–Prince 5(4), SciPy's default.

tsit5value
tsit5

Tsitouras 5(4): usually fewer evaluations than RK45 for the same accuracy.

bdfvalue
bdf

Variable-order BDF/NDF (1–5), stiff.

radauvalue
radau

Radau IIA order 5, stiff (L-stable; the most accurate stiff choice at tight tolerances).

final class OdeEvent

An event function g(t, y); solveIvp finds its zeros.

Constructors

OdeEventconstructor
const OdeEvent(this.g, {this.terminal = false, this.maxCount = 1, this.direction = 0})
Example
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)})');
}
Output
lands at t = 1.427843 s (√(20/9.81) = 1.427843)

Properties

gfield
final double Function(double t, Float64List y) g
final bool terminal

Stop the integration after maxCount zeros.

final int maxCount
final double direction
0: only zeros where g goes from negative to positive; < 0: positive to negative; 0: both.
final class OdeSolution

The result of solveIvp.

Properties

tfield
final List<double> t

Output times (every accepted step, or the requested ones) and the states there.

yfield
final List<Float64List> y
solfield
final OdeInterpolant? sol

The continuous solution over the whole interval, when denseOutput: true.

tEventsfield
final List<List<double>> tEvents

Per event: the times and states of its zeros.

yEventsfield
final List<List<Float64List>> yEvents
nfevfield
final int nfev
njevfield
final int njev
nlufield
final int nlu
statusfield
final int status

0: reached the end; 1: a terminal event; -1: the integration failed.

messagefield
final String message
stepsfield
final int steps

Accepted steps.

successgetter
bool get success
final class OdeInterpolant

A piecewise continuous solution made of the steps' interpolants.

Constructors

OdeInterpolantconstructor
OdeInterpolant(this.segments, this.n)
Example
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)}');
}
Output
8 segments; y(1) = 0.5403

Properties

final List<DenseSegment> segments
nfield
final int n
tMingetter
double get tMin
tMaxgetter
double get tMax

Methods

callmethod
Float64List call(double t, [Float64List? out])

y(t) into out (allocated when null). Times outside the range extrapolate the nearest segment.

Example
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)})');
}
Output
y(2) = (-0.41614690, -0.90929689)
enum SymplecticMethod

Values

velocityVerlet

Kick-drift-kick with the acceleration cached between steps: order 2, one force evaluation per step.

leapfrog

Drift-kick-drift (position Verlet): order 2, one force evaluation per step, no cached state.

yoshida4

Yoshida's triple jump over velocity Verlet: order 4, three force evaluations per step.

yoshida6

Yoshida's solution A, seven Verlet substeps: order 6, seven force evaluations per step.

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 compositionWeights
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)
Example
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)');
  }
}
Output
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

methodfield
final SymplecticMethod method
accelfield
final AccelerationFunction accel
nfield
final int n
nfevfield
int nfev

Force evaluations so far.

ordergetter
int get order

Order of accuracy.

Methods

void invalidate()

Call after changing q outside step (the cached acceleration is stale).

Example
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()}');
}
Output
q = [1.999888, 0.019999]
stepmethod
void step(Float64List q, Float64List v, double h)

One step of size h; q and v are updated in place.

Example
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)}');
}
Output
circular orbit radius after 64 steps: 0.99999965
integratemethod
void integrate(Float64List q, Float64List v, double h, int steps)

steps steps of size h.

Example
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)})');
}
Output
after one period: q = (0.99999, -0.00339)
final class OptimizeResult

The outcome of a minimisation or a multivariate root/least-squares solve (SciPy's OptimizeResult).

Constructors

OptimizeResultconstructor
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})
Example
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}');
}
Output
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

xfield
final Float64List x

The solution.

funfield
final double fun

The objective at x (for least squares, \tfrac{1}{2}\Vert r\Vert^{2}; for systems, \tfrac{1}{2}\Vert F\Vert^{2}).

nitfield
final int nit

Iterations.

nfevfield
final int nfev

Function evaluations (a value-and-gradient call counts once).

njevfield
final int njev

Jacobian or gradient evaluations, where counted separately.

successfield
final bool success
messagefield
final String message
gradfield
final Float64List? grad

The gradient at x, when the method computes it.

final Float64List? residual

The residual vector at x (least squares and systems).

Methods

toStringmethod
String toString()
Example
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])));
}
Output
OptimizeResult(success: true, fun: 7.703719777548943e-32, nit: 3, nfev: 4, message: converged, x: [-1.6653345369377348e-16, 1.0000000000000002])
final class ScalarResult

The outcome of a scalar root or scalar minimisation.

Constructors

ScalarResultconstructor
const ScalarResult(this.x, this.fun, this.iterations, this.evaluations, this.converged, this.message)
Example
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}');
}
Output
ScalarResult(x: 1.414, fun: 0.0, iterations: 5, converged: true)
x = 1.414, iterations 5

Properties

xfield
final double x
funfield
final double fun

f(x) (the residual for a root, the minimum for a minimisation).

final int iterations
final int evaluations
final bool converged
messagefield
final String message

Methods

toStringmethod
String toString()
Example
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));
}
Output
ScalarResult(x: 1.4142135623731364, fun: 1.1723955140041653e-13, iterations: 8, converged: true)
class OptimizeException implements Exception

Thrown when an input is invalid (bracket without a sign change, infeasible bounds...).

Constructors

OptimizeException(this.message)
Example
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'));
}
Output
caught: f(a) and f(b) must have different signs
OptimizeException: custom

Properties

messagefield
final String message

Methods

toStringmethod
String toString()
Example
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'));
}
Output
OptimizeException: line search failed
final class WolfeLineSearch

A line search along p from x: evaluates the objective and gradient at x + \alpha p into xTrial / gTrial.

Constructors

WolfeLineSearchconstructor
WolfeLineSearch(this.fg, int n)
Example
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');
}
Output
step length α = 0.5

Properties

fgfield
final ValueAndGradient fg
xTrialfield
final Float64List xTrial
gTrialfield
final Float64List gTrial
int evaluations

Evaluations made by the last search.

phiStargetter
double get phiStar

Methods

searchmethod
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.

Example
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)}');
}
Output
α = 1.0
with c2 = 0.1 (strict): α = 1.0
class

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

Sobolconstructor
Sobol(this.dims, {Int32List? shift})
Example
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]})']}');
}
Output
first points: [(0.0, 0.0), (0.5, 0.5), (0.75, 0.25), (0.25, 0.75)]

Static

bitsconstant
static const int bits = 30
maxDimsconstant
static const int maxDims = 1024
randomShiftstaticmethod
static Int32List randomShift(int dims, math.Random rng)

A random digital shift for dims dimensions.

Example
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');
}
Output
shift [458359283, 1043999694]
shifted first points: [0.42688034754246473, 0.9723004829138517, 0.9268803475424647, 0.47230048291385174]

Properties

dimsfield
final int dims
indexgetter
int get index

Points drawn so far.

Methods

nextIntomethod
void nextInto(Float64List out)

The next point into out (length dims).

Example
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);
  }
}
Output
[0.0, 0.0, 0.0]
[0.5, 0.5, 0.5]
[0.75, 0.25, 0.25]
[0.25, 0.75, 0.75]
takemethod
Float64List take(int n)

The next n points, n x dims row-major.

Example
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)}');
}
Output
[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]
final class QuadResult

The outcome of an adaptive quadrature.

Constructors

QuadResultconstructor
const QuadResult(this.value, this.error, this.evaluations, {this.intervals = 1, this.status = 0})
Example
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}');
}
Output
QuadResult(3.14159 ± 1e-9, 63 evaluations, status 0)
value 3.14159, error 1e-9, evaluations 63, status 0

Properties

valuefield
final double value

The estimate of the integral.

errorfield
final double error

An estimate of |value − integral|.

final int evaluations

Integrand evaluations.

final int intervals

Subintervals used.

statusfield
final int status

QUADPACK'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.

convergedgetter
bool get converged

Methods

toStringmethod
String toString()
Example
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));
}
Output
QuadResult(3.139592654256459 ± 4.381015884524921e-11, 819 evaluations, status 0)