Calculus
New to calculus at the prompt? R4 — Calculus walks through derivatives, integrals and limits in one short lesson. This page is the reference.
import it.grypho.scala.leonardo.core.*
import it.grypho.scala.leonardo.scalar.*
val x = _Variable("x")
val env = new Environment()
Symbolic differentiation
derive(e, v) applies the standard differentiation rules and returns a symbolic expression. The chain rule, product rule, and quotient rule are all handled:
derive(Power(x, _Number(3.0)), x).toString
// res0: String = "(3.0 * (x ^ 2.0))"
// d/dx sin(x^2) = cos(x^2) * 2x (chain rule)
derive(Sin(Power(x, _Number(2.0))), x).toString
// res1: String = "(cos((x ^ 2.0)) * (2.0 * x))"
// d/dx (x * exp(x)) = exp(x) + x*exp(x) (product rule)
derive(Product(x, Exp(x)), x).toString
// res2: String = "(exp(x) + (x * exp(x)))"
Combine with simplify or simplifyFully to reduce the result:
simplifyFully(derive(Product(x, Exp(x)), x)).toString
// res3: String = "(exp(x) + (x * exp(x)))"
The hyperbolic and reciprocal-trigonometric functions (sinh/cosh/tanh, asinh/acosh/atanh, sec/csc/cot, sech/csch/coth) are first-class nodes with the standard rules:
// d/dx tanh(x) = sech(x)^2
derive(Tanh(x), x).toString
// res4: String = "(sech(x) ^ 2.0)"
Higher-order derivatives
Wrap the result in a second derive call (or use _Derivative nodes):
// d²/dx² x^4 = 12x²
val d2 = derive(derive(Power(x, _Number(4.0)), x), x)
// d2: _Expression = Product(
// a = _Number(4.0),
// b = Product(
// a = _Number(3.0),
// b = Power(base = _Variable("x"), exp = _Number(2.0))
// )
// )
simplifyFully(d2).toString
// res5: String = "(12.0 * (x ^ 2.0))"
Evaluating a derivative numerically
val slope = derive(Sin(x), x) // should be cos(x)
// slope: _Expression = Cos(_Variable("x"))
val envPi2 = new Environment(5, Map("x" -> _Number(math.Pi / 2)))
// envPi2: Environment = it.grypho.scala.leonardo.core.Environment@54ac862e
slope.eval(envPi2) // cos(π/2) ≈ 0
// res6: Either[_Expression, _Value] = Right(_Number(6.123233995736766E-17))
Indefinite integration
integrate(e, v) applies the symbolic rule table (linearity, power rule, exp/sin/cos, 1/x → log, linear-argument chain rule):
integrate(Power(x, _Number(2.0)), x).toString
// res7: String = "((x ^ 3.0) / 3.0)"
integrate(Sin(x), x).toString
// res8: String = "(-1.0 * cos(x))"
// ∫ 1/x dx = log(x)
integrate(Ratio(_Number(1.0), x), x).toString
// res9: String = "ln(x)"
// Chain rule: ∫ sin(3x) dx = -cos(3x)/3
integrate(Sin(Product(_Number(3.0), x)), x).toString
// res10: String = "((-1.0 * cos((3.0 * x))) / 3.0)"
Beyond the linear chain rule, non-linear u-substitution closes ∫ f(g(x))·g'(x) dx: the engine tries candidate inner functions g, divides the integrand by g', and integrates in g only when the quotient is free of x.
// ∫ x·e^(x²) dx = e^(x²)/2 (u = x²)
integrate(Product(x, Exp(Power(x, _Number(2.0)))), x).toString
// res11: String = "(exp((x ^ 2.0)) / 2.0)"
When every rule declines, the integrand is put into a standard form and tried again term by term: constants are folded and moved out of a denominator, powers of one base are merged (2*x*x^(1/2) is 2·x^(3/2)), a reciprocal power is read as a negative one (1/x^(3/2)) and a polynomial power is expanded. The textbook substitutions follow: ln(u) times a function by parts (ln(x)/x^2), sin(x)^m*cos(x)^n with one odd power by w = cos(x) or sin(x), sin(x)*cos(x) as sin(2x)/2, u = a*x + b for a polynomial times a power of a*x + b (x*(1 - x)^(1/2)), w = x^2 for x^3*(1 + x^2)^(1/2), x = u^q for fractional powers (x^(1/2)/(x^2 + x)), x = e^u for cos(ln(x)), and exp(a*x)*sin(b*x) / cos in closed form for any numeric slopes. None of this runs for an integral that already closed, so no earlier answer changes.
The logarithm in an antiderivative is written ln(u), not ln|u|: integral(80/(16 - x^2), x) contains ln(x - 4), which is complex on (-4, 4). That is a correct antiderivative (it differs from the real one by a constant), and a definite integral through it is real, since the imaginary parts cancel.
Radical integrands close by trigonometric / hyperbolic substitution; √(a²+x²) and √(x²−a²) use the hyperbolic substitution, so the result is written with the asinh/acosh functions:
// ∫ dx/√(x²+1) = asinh(x)
integrate(Ratio(_Number(1.0), Power(Sum(Power(x, _Number(2.0)), _Number(1.0)), _Number(0.5))), x).toString
// res12: String = "asinh(x)"
Classic non-elementary integrals are answered with their named special functions — the trigonometric integrals Si/Ci, the exponential integral Ei, the logarithmic integral li, the Fresnel integrals fresnelS/fresnelC, and the error function erf — symbolic nodes with numeric kernels, so the antiderivative still evaluates:
// ∫ sin(x)/x dx = Si(x)
integrate(Ratio(Sin(x), x), x).toString
// res13: String = "Si(x)"
Unsupported forms are left as _Integral nodes (symbolic, not an error):
integrate(Sin(Product(x, x)), x).toString // sin(x²) has no closed form
// res14: String = "integral(sin((x * x)), x)"
Vector calculus
The gradient grad, divergence div, curl curl, Laplacian laplacian, Jacobian jacobian and Hessian hessian take a field followed by the ordered coordinate tuple — the order is never inferred, because it fixes the order of the result’s components. grad, laplacian and hessian take a scalar field, div, curl and jacobian a vector field, which is an n×1 matrix. jacobian and hessian are Cartesian only: in a curvilinear system they need connection terms, and they stay symbolic rather than answer the Cartesian formula.
import it.grypho.scala.leonardo.vector.*
import it.grypho.scala.leonardo.matrix._Matrix
val y = _Variable("y")
// y: _Variable = _Variable("y")
// grad(x^2 * y) = [2xy, x^2]^T
_Grad(Product(Power(x, _Number(2.0)), y), Vector(x, y)).eval(env).toExpression.toString
// res15: String = "[[((2.0 * x) * y)], [(x ^ 2.0)]]"
The coordinate-free identities hold, which makes them the natural property tests: curl(grad f) = 0, div(curl F) = 0, and laplacian is defined as div ∘ grad so the two cannot disagree. Shapes that have no meaning — a curl outside three dimensions, a component/coordinate count mismatch, a repeated coordinate — stay symbolic rather than being guessed.
Cartesian, cylindrical and spherical coordinates are all supported, through one set of orthogonal-curvilinear formulas parameterised by the system’s scale factors — Cartesian is simply the case where they are all 1:
val r = _Variable("r")
val th = _Variable("t")
val ph = _Variable("p")
val atPoint = new Environment(variables =
Map("r" -> _Number(2.0), "t" -> _Number(0.7), "p" -> _Number(0.4)))
The Newtonian potential is harmonic away from the origin — ∇²(1/r) = 0 — and that is a sharp check on the scale factors, since a single wrong one breaks it. The symbolic form does not visibly collapse (simplify does no common-factor cancellation), so evaluate it:
_Laplacian(Ratio(_Number(1.0), r), Vector(r, th, ph), CoordinateSystem.Spherical).eval(atPoint)
// res16: Either[_Expression, _Value] = Right(_Number(0.0))
cylindrical is (r, θ, z); spherical is (r, θ, φ) with θ the polar angle (physics) and sphericalmaths has θ azimuthal and φ polar (mathematics). All are three-dimensional, and the coordinates are identified by position, not by name — so the two spherical keywords differ in argument order, not in naming. Exchanging the last two coordinates flips the handedness of the basis, so curl, a pseudo-vector, carries the matching sign; the two conventions agree on the curl of the same physical field.
Definite integration
_DefIntegral(e, v, lo, hi) answers F(hi) − F(lo) when the indefinite integral closes and its antiderivative is smooth across the whole interval (exact in exact mode), and otherwise integrates numerically by certified adaptive Simpson, to five digits beyond the display precision. An integral across a pole, or one that does not settle within its evaluation budget, stays unevaluated rather than answering a wrong number: integral(1/(x - 2), x, 0, 3) and integral(sec(x)^2, x, -pi, pi) decline.
An improper integral — an infinite limit, or an endpoint the integrand is undefined at — is lim F(b) − lim F(a) when the antiderivative closes and is smooth across the open interval: integral(exp(-x), x, 0, inf) is 1, integral(exp(-x^2), x, -inf, inf) is √π, integral(ln(x), x, 0, 1) is -1, and integral(1/x, x, 1, inf) is inf, the divergence it has. ∞ − ∞, or an antiderivative with no limit at an end (integral(sin(x), x, 0, inf)), stays unevaluated.
The limits are children, not binders: only v is bound, so a limit may be any expression and may name other variables. That is what gives iterated integration with variable limits (integral(integral(x*y, y, 0, x), x, 0, 1)) for free — the inner limit is an ordinary free occurrence of the outer variable, bound per sample by the outer pass. In the grammar the limits are full expressions too, so integral(sin(x), x, 0, 2*pi) is written as it reads.
The numeric path uses a compiled Double ⇒ Double closure when the integrand is free of unresolvable nodes — no per-step allocation:
// ∫₀¹ x² dx = 1/3
_DefIntegral(Power(x, _Number(2.0)), x, _Number(0.0), _Number(1.0)).eval(env)
// res17: Either[_Expression, _Value] = Right(_Number(0.3333333333333333))
// ∫₀π sin(x) dx = 2
_DefIntegral(Sin(x), x, _Number(0.0), _Number(math.Pi)).eval(env)
// res18: Either[_Expression, _Value] = Right(_Number(2.0))
// ∫₁ᵉ 1/x dx = 1 (ln e − ln 1)
_DefIntegral(Ratio(_Number(1.0), x), x, _Number(1.0), _Number(math.E)).eval(env)
// res19: Either[_Expression, _Value] = Right(_Number(1.0))
Function sampling
sample(e, v, lo, hi, n, env) evaluates an expression over a uniform grid of n points in [lo, hi], returning Vector[(Double, Double)] with non-finite results silently dropped:
val pts = sample(Sin(x), x, 0.0, math.Pi, 5, env)
pts.length
// res20: Int = 5
pts.map { (xi: Double, yi: Double) => f"($xi%.4f, $yi%.4f)" }
// res21: Vector[String] = Vector(
// "(0.0000, 0.0000)",
// "(0.7854, 0.7071)",
// "(1.5708, 1.0000)",
// "(2.3562, 0.7071)",
// "(3.1416, 0.0000)"
// )
The fast path compiles the expression to a Double ⇒ Double closure (no per-step allocation). A fallback per-step eval handles non-compilable nodes like _Derivative.
Compiled closures over several variables
Code that evaluates the same model thousands of times — an optimiser’s cost and Jacobian, a controller’s prediction — can compile it once. compile(e, vars, env) returns a closure over an Array[Double] read in the order of vars, and compileMatrix(m, vars, env) does the same for a matrix, returning its cells row-major. Both are built from the same table as the one-variable form, so they decline exactly what it declines (None), and any other free name must be bound in env. This is library API; the REPL needs none.
val model = Sum(Product(Power(x, _Number(2.0)), y), Sin(y))
val fast = compile(model, Seq(x, y), env)
fast.map(f => f(Array(2.0, 0.5)))
// res22: Option[Double] = Some(2.479425538604203)
A Jacobian is a symbolic matrix once evaluated, so it compiles cell by cell:
val field = _Matrix.ofRows(Vector(model), Vector(Product(x, y)))
val jac = _Jacobian(field, Vector(x, y)).eval(env).left.toOption
val fastJ = jac.flatMap(j => compileMatrix(j, Seq(x, y), env))
fastJ.map(f => f(Array(2.0, 0.5)).toVector)
// res23: Option[Vector[Double]] = Some(
// Vector(2.0, 4.877582561890373, 0.5, 2.0)
// )
Measured on the JVM (F_0058), a compiled 3×3 Jacobian evaluates 7–10 times faster than walking the tree with eval, and within 1.3–1.6× of the same cells written by hand in Scala. The remaining gap to hand-written code is the cost of the functions themselves (exp, sin, ln), which compilation cannot remove.
The Syntax extension gives method-call form:
import it.grypho.scala.leonardo.scalar.Syntax.*
val pts2 = Sin(x).sample(x, 0.0, math.Pi, 5, env)
pts2 == pts
// res24: Boolean = true
Systems of differential equations
ode(rhs, y, t, t0, y0, target) solves the initial-value problem y' = rhs(t, y), y(t0) = y0, at target. When y0 is a column the problem is a system: a constant-coefficient linear one closes through the matrix exponential, and a time-varying or nonlinear one is integrated numerically. The state may be one name bound to the whole column (A(t)*y, or components read with at(y, i, 1)) or a column of names, each bound to its component, so a system reads as written:
import it.grypho.scala.leonardo.parser.Parser
import it.grypho.scala.leonardo.ode.*
def run(s: String) = Parser.parse(s) match
case Parser.Success(e, _) => e.eval(env)
case other => sys.error(other.toString)
// x'' = -x as x' = v, v' = -x, from (1, 0): the answer is (cos 1, -sin 1)
run("ode([[v], [-x]], [[x], [v]], t, 0, [[1], [0]], 1)")
// res25: Either[_Expression, _Value] = Right([[0.5403], [-0.84147]])
// Lotka-Volterra predator-prey, nonlinear
run("ode([[x - x*y], [x*y - y]], [[x], [y]], t, 0, [[2], [1]], 5)")
// res26: Either[_Expression, _Value] = Right([[1.00513], [0.40638]])
The answer is certified by step doubling: fourth-order Runge–Kutta runs with n and 2n steps, and the state is returned only when the two agree within the tolerance = uses (0.5·10^-precision), relative to the largest state component of the run — so a problem written in other units is answered or refused alike. An explicit method on a stiff system produces a finite, confident and wrong number; here it produces a refusal instead, and the node’s detailed says why — the reason the REPL appends as a note:
Parser.parse("ode([[-1000000 * (y - cos(t))]], [[y]], t, 0, [[0]], 1)") match
case Parser.Success(s: _ODESystem, _) => s.detailed(env)
case other => sys.error(other.toString)
// res27: Either[OdeFailure, Vector[Double]] = Left(NonFinite(0.0285))
The integrator is also public as a step and a trajectory, the method always named — euler, rk4, or the adaptive Dormand–Prince rk45: odeStep(F, y, t, t0, y0, h, method) is the state at t0 + h, and odeSolve(F, y, t, t0, y0, t1, h, method) the trajectory, one row [t, state…] per output time, t1 always the last. These are not certified: the step is the caller’s choice, which is what a controller simulation wants. For rk45, h is the spacing of the output rows and the steps between them are chosen to hold the tolerance.
run("odeSolve([[v], [-x]], [[x], [v]], t, 0, [[1], [0]], 0.3, 0.1, rk4)")
// res28: Either[_Expression, _Value] = Right(
// [[0.0, 1.0, 0.0], [0.1, 0.995, -0.09983], [0.2, 0.98007, -0.19867], [0.3, 0.95534, -0.29552]]
// )