SPB Git

Repository Public MIT

API.md 12.4 KB

# ORIXSymbolic — API reference

Symbolic layer of ORIX Calc. Depends on ORIXExpression (the Expr tree, parser, printer) and ORIXNumerics (explanations, verification, root finding, quadrature). No UI, no global state: every function is a pure static func on the Symbolic namespace and can be called from any thread.

swift
import ORIXExpression
import ORIXSymbolic

let f = try Symbolic.parse("x^2 * sin(x)")          // same as Parser.parse

# The contract: every result says what it is

swift
public enum ResultKind { case exact, symbolic, numerical, unsupported, failedConvergence }
kind meaning what to show
.exact exact value (number, or closed form in √, π, e, ln, i) the expression, optionally the decimal reading
.symbolic exact expression with free variables (derivative, antiderivative, simplified form) the expression
.numerical floating-point approximation from a numerical method "≈ value", the error estimate, a "numerical" badge
.unsupported outside the implemented rules, or refused (DEG mode, singularity, too large) note
.failedConvergence a numerical method ran and did not converge note

A numerical value is never returned with kind .exact/.symbolic, and a numerical result never carries an expression.

Most operations return a SymbolicResult:

swift
public struct SymbolicResult {
    var kind: ResultKind
    var expression: Expr?             // nil when unsupported or purely numerical
    var values: [Value]               // numerical value(s); the decimal reading of an exact constant
    var errorEstimate: Double?        // numerical results
    var explanation: Explanation      // ORIX Explain: the rules actually applied, in order
    var verification: VerificationReport   // ORIX Verified Results: the checks actually run
    var note: String                  // why unsupported, assumptions, what a numerical value means
    var hasConstantOfIntegration: Bool
    var isSuccess: Bool               // exact, symbolic or numerical
    var doubleValue: Double?
    var text: String                  // pretty text; appends " + C" for an indefinite integral
    func text(style: PrintStyle, constantOfIntegration: Bool = true) -> String    // .pretty / .ascii / .latex
}

Show verification.isVerified as the verified badge, verification.warnings as cautions, and explanation.steps (label / expression / value) in the Explain panel. explanation.assumptions lists conventions ("Angles are in radians", "a ≠ 0", "|r| < 1").

Printing. Use result.text or Symbolic.string(expr, style:) for expressions produced by this package. They are the same as Printer.string but safe for deep trees (see the note at the end).

Options.

swift
public struct SymbolicOptions { var angleMode: AngleMode = .radians; var assumePositive = false }
  • angleMode: symbolic calculus is done in radians. If you pass .degrees or .gradians, any operation whose input contains a trigonometric function returns .unsupported with a message asking for RAD. Expressions without trigonometry work in every mode. Recommended: run the Math screen in radians, or surface the message.
  • assumePositive (Simplify only): treats every variable as a positive real, enabling √(x²) → x, ln(ab) → ln a + ln b, ln(xᵃ) → a·ln x, |x| → x.

# Simplify tab

swift
Symbolic.simplify(P("(x^2-1)/(x-1) + sin(x)^2 + cos(x)^2")).text      // "x + 2"
Symbolic.simplify(P("sqrt(x^2)")).text                                 // "|x|"
Symbolic.simplify(P("sqrt(x^2)"), options: .init(assumePositive: true)).text   // "x"
Symbolic.expand(P("(x+1)^3")).text                                     // "x³ + 3x² + 3x + 1"
Symbolic.factor(P("2x^3+4x^2+2x")).text                                // "2x · (x + 1)²"
Symbolic.factor(P("x^2+1")).note                                       // "The polynomial is irreducible over the rationals."

factor(_:variable:) handles one-variable polynomials with rational coefficients; anything else is .unsupported. Polynomial is public for direct use:

swift
let p = Polynomial(P("x^3 - 6x^2 + 11x - 6"), variable: "x")!        // nil when not a rational polynomial
p.degree; p.coefficients                                             // ascending BigRational coefficients
let (q, r) = p.dividing(by: Polynomial(integers: [-1, 1]))           // p = q·(x − 1) + r
Polynomial.gcd(p, q); p.derivative; p.evaluate(BigRational(1, 2)); p.composed(with: q)
p.factorized()                // Factorization: content, [PolynomialFactor(polynomial, multiplicity, isProvenIrreducible)]
Symbolic.polynomialRoots(p)   // PolynomialRootsResult: roots (expression?, real, imaginary, multiplicity, kind, residual)

# Derivative tab

swift
let d = Symbolic.differentiate(P("x^2*sin(x)"), variable: "x")      // order: 1 by default
d.text                                                               // "x² · cos(x) + 2x · sin(x)"
d.explanation.plainText                                              // Product rule … u = x², v = sin(x) …
Symbolic.differentiate(P("x^5"), variable: "x", order: 3)            // 60x²
Symbolic.differentiate(P("x^2*y^3"), variables: ["x", "y"])          // ∂²/∂x∂y → 6x·y²
Symbolic.gradient(P("x^2*y + sin(y)"), variables: ["x", "y"]).text   // "[2x · y, x² + cos(y)]"

The verification compares the symbolic derivative with a numerical (Ridders) derivative at sample points. Unsupported: gamma, factorial, min/max, if/piecewise, comparisons, vectors. |x|′ = sign(x) is returned with the assumption "not differentiable at 0".

# Integral tab

swift
let i = Symbolic.integrate(P("x*e^x"), variable: "x")               // indefinite
i.text                              // "x · exp(x) − exp(x) + C"   (the Expr has no "+ C")
i.verification                      // "Differentiate the antiderivative": passed
Symbolic.integrate(P("e^(-x^2)"), variable: "x").kind               // .unsupported, note: "No closed form found…"

let a = Symbolic.integrate(P("sin(x)"), variable: "x", from: P("0"), to: P("pi"))     // .exact, "2"
let n = Symbolic.integrate(P("e^(-x^2)"), variable: "x", from: P("0"), to: P("1"))    // .numerical
n.doubleValue; n.errorEstimate      // 0.746824132812…, ~1e-12
Symbolic.integrate(P("1/x"), variable: "x", from: P("-1"), to: P("1")).kind           // .unsupported (singularity at 0)
Symbolic.integrate(P("1/(1+x^2)"), variable: "x", from: P("-inf"), to: P("inf")).text // "π"

Bounds are expressions (inf, -inf, pi/2, …). Definite-integral outcomes: exact value (antiderivative found, no discontinuity detected, cross-checked by quadrature) · .numerical with errorEstimate (no antiderivative, or piecewise integrand) · .unsupported (singularity inside the interval, integrand not real on part of it) · .failedConvergence · .exact with expression inf/−inf and a "diverges" note · .symbolic with a warning when bounds or integrand contain parameters.

# Limit tab

swift
let l = Symbolic.limit(P("sin(x)/x"), variable: "x", to: .zero)                    // direction: .both (default), .left, .right
l.kind; l.behavior; l.text          // .exact, .finite, "1"
Symbolic.limit(P("(1+1/x)^x"), variable: "x", to: P("inf")).text                   // "e"
let none = Symbolic.limit(P("1/x"), variable: "x", to: .zero)
none.behavior; none.leftText; none.rightText                                        // .doesNotExist, "−∞", "∞"
Symbolic.limit(P("sqrt(x^2+x)-x"), variable: "x", to: P("inf"))                    // .numerical, value 0.5, errorEstimate

LimitResult: kind, behavior (.finite, .positiveInfinity, .negativeInfinity, .doesNotExist, .undetermined), expression (exact value, or inf / −inf), value, errorEstimate, leftText, rightText, explanation, verification, note, text.

# Series tab

swift
let s = Symbolic.taylor(P("sin(x)"), variable: "x", around: .zero, order: 5)
s.text            // "x − x³/6 + x⁵/120 + O(x⁶)"
s.expression      // the polynomial only
s.coefficients    // [Expr] c₀…c₅ ;  s.order == 5 ;  s.remainder == "O(x⁶)"

Symbolic.sum(P("k^2"), index: "k", from: P("1"), to: P("n")).text        // "n · (2n + 1) · (n + 1)/6"
Symbolic.sum(P("(1/2)^k"), index: "k", from: P("0"), to: P("inf")).text  // "2"  (note: convergent, |r| < 1)
Symbolic.sum(P("1/k"), index: "k", from: P("1"), to: P("4")).text        // "25/12"

# Solve tab

swift
let r = Symbolic.solve(P("x^2 - 5x + 6 = 0"), for: "x")          // an expression without "=" is read as "= 0"
r.kind                      // .exact
r.solutions.map(\.text)     // ["2", "3"]
r.explanation.plainText     // Quadratic formula … Δ = 1 …
Symbolic.solve(P("x^2+1=0"), for: "x").solutions.map(\.text)     // ["−i", "i"]; realSolutions is empty
Symbolic.solve(P("sqrt(x+1)=x-1"), for: "x").rejected            // ["x = 0: extraneous, residual 2.0e+00"]
Symbolic.solve(P("cos(x)=x"), for: "x", in: -10...10)            // .numerical, roots in the interval only

SolveResult: kind, solutions: [Solution] (real ones first, increasing), realSolutions, rejected, isIdentity, explanation, verification, note. Solution: expression?, real, imaginary, isReal, multiplicity, kind, residual, text. For trigonometric equations the principal solutions are returned and note gives the general solution. The in: interval is used only by the numerical fallback (default [−10, 10]).

# System tab

swift
let s = Symbolic.solveLinearSystem([P("2x+y=5"), P("x-y=1")], variables: ["x", "y"])
s.classification            // .unique / .none / .infinitelyMany
s.solution                  // ["x": 2, "y": 1] as Expr; parametric in s.freeVariables when infinitely many
s.values; s.rank

let n = Symbolic.solveSystem([P("x^2+y^2=4"), P("x*y=1")], variables: ["x", "y"],
                             guesses: [[1, 1]], searchBox: -10...10)
n.kind                      // .numerical (or .exact when the system is linear: see n.linear)
n.solutions                 // [SystemSolution(values, residual, iterations)]

# ODE tab

swift
let o = Symbolic.solveODE([P("-2y")], states: ["y"], independent: "t", initial: [1], from: 0, to: 3,
                          method: .dormandPrince(relativeTolerance: 1e-8, absoluteTolerance: 1e-10))   // or .rk4(steps: 1000)
o.kind                      // .numerical, or .failedConvergence (blow-up / stiffness) with the partial trajectory
o.times; o.values           // trajectory: values[k] is the state vector at times[k]
o.finalState; o.finalErrorEstimate; o.statistics   // accepted / rejected steps, evaluations, smallest / largest step
o.value(of: "y", at: 1.5)   // linear interpolation for plotting

Symbolic.solveSecondOrderODE(P("-y"), state: "y", derivative: "v", initialValue: 1, initialDerivative: 0, from: 0, to: 10)

# Optimize tab

swift
let m = Symbolic.optimize(P("x^3-3x"), variable: "x", from: P("-3"), to: P("3"))
m.criticalPoints            // [CriticalPoint]: location?, x, valueExpression?, value, classification, secondDerivative, kind
m.endpoints; m.globalMinimum; m.globalMaximum      // global extrema include the endpoints
m.kind                      // .exact when every critical point has a closed form, else .numerical

let z = Symbolic.minimize(P("(1-x)^2+100(y-x^2)^2"), variables: ["x", "y"], start: [-1.2, 1])     // also maximize(…)
z.point; z.value; z.gradientNorm; z.kind            // always .numerical: a local minimum from the starting point

# Notes for integration

  • Threading / stack. Expression trees are processed recursively (also by Printer and CompiledExpression). Each public function runs its work synchronously on a dedicated thread with a 64 MB stack, so it is safe to call from a Swift concurrency task or a GCD queue. Calls are blocking; run them off the main actor for long problems.
  • Bounds. Inputs above 20 000 nodes or nesting depth 400 are refused (.unsupported, "too large"). All searches have explicit caps (integration rule budget, L'Hôpital count, derivative size, Kronecker candidates, ODE steps).
  • Printing deep results. Calling Printer.string directly from a secondary thread on a result with a long sum can overflow that thread's stack; use result.text / Symbolic.string.
  • Special names. inf is infinity, i the imaginary unit, e and pi the constants; log(x) is base 10, ln(x) natural.
Files main
Menu

Theme