Expressions

Expressions

An expression is a tree: numbers, variables and constants at the leaves, operations and functions above them. This package uses the same tree as analytic and graphics, so nothing needs converting between them.

Writing one

sym(text) reads calculator notation and returns an Expr. Numbers are exact: 0.1 is the fraction 1/10, not a floating-point number.

import { sym } from "@ratmath/symbolic";

const f = sym("2x^2 + 3sin(x) - 0.5");
String(f);            // "2*x^2 + 3*sin(x) - 1/2"
f.variables;          // ["x"]
f.toTeX();            // "2\\,x^{2} + 3\\,\\sin\\left(x\\right) - \\frac{1}{2}"
f.tree;               // the plain tree: { type: "op", op: "-", args: [...] }

The grammar is the one the rest of RatMath uses: + - * / ^, parentheses, implicit multiplication after a number or a closing bracket (2x, 3(x + 1), 2sin(x)), ^ binding tighter than a leading minus (so -x^2 is −(x2)-(x^2)), and the functions sqrt cbrt abs exp log sin cos tan asin acos atan sinh cosh tanh. log and ln are both the natural logarithm. pi and e are the constants.

The tree

A tree node is one of five plain objects:

{ type: "num", value: Rational }
{ type: "var", name: "x" }
{ type: "const", name: "pi" }            // or "e"
{ type: "op", op: "+", args: [a, b] }    // + - * / ^ and "neg" with one argument
{ type: "call", name: "sin", args: [a] }

Every function of this package accepts text, an Expr or such a tree, and expr.tree hands the tree to analytic's fn or graphics' plots. The builders num, v, op and call make nodes directly.

Substituting, differentiating, evaluating

const g = sym("x^2 + y");
String(g.subs({ x: "y + 1", y: "x" }));   // "(y + 1)^2 + x"   (both at once)
String(sym("x^2*sin(x)").diff("x"));      // "2*x*sin(x) + x^2*cos(x)"

const iv = sym("sqrt(2) + pi").evaluate({}, 64);   // a Core RationalInterval certain to hold the value
sym("x/3").approx({ x: 1 });                       // 0.3333333333333333, the midpoint of such an interval

evaluate is certified: the interval it returns has exact rational ends and is guaranteed to contain the true value. It is what the rest of the package uses to tell two expressions apart. It takes exact values for the variables and a number of bits of accuracy, and throws where the expression is undefined.

Mathematically, substitution is composition of functions and the tree is the function's definition; two different trees can define the same function. Deciding when they do is the subject of Normal forms and Equality. a.same(b) only asks whether the trees are identical.

Try itEdit the code and run it with @ratmath/symbolic and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs