symcompR is a computer algebra system written in R. It is a native port of the Python library SymPy: expressions are ordinary R objects, exact integers and rationals are stored with the gmp package, and every algorithm runs in R. Results follow SymPy closely, down to the order in which terms print, so code and answers move between the two systems with little translation.
This vignette introduces the building blocks: symbols, exact numbers, constants, printing, substitution, numerical evaluation, and turning expressions into R functions. The other vignettes cover each area of the package in depth; they are listed at the end.
Symbols
A symbol is a named mathematical variable. Create one with
Symbol(), or several at once with
sym_symbols(), which returns a named list.
x <- Symbol("x")
y <- Symbol("y")
x + y + x
#> 2*x + y
xyz <- sym_symbols("a b c")
xyz$a * xyz$b^2
#> a*b^2
sym_symbols("t0:3")
#> $t0
#> t0
#>
#> $t1
#> t1
#>
#> $t2
#> t2sym_var() creates symbols and assigns them in the
calling environment, the way var() does in SymPy.
sym_var("u v")
u^2 - v^2
#> u^2 - v^2Assumptions
Symbols can carry assumptions such as positive,
integer, or real. Assumptions change what
simplifications are valid. In general \sqrt{x^2} \neq x, but it is true for a
positive x:
sqrt(x^2)
#> sqrt(x^2)
p <- Symbol("p", positive = TRUE)
sqrt(p^2)
#> p
n <- Symbol("n", integer = TRUE)
cos(2 * sym_pi * n)
#> 1
(-1)^(2 * n)
#> 1The queries is_positive(), is_integer(),
is_real(), and friends follow SymPy’s three valued logic:
TRUE, FALSE, or NA when the
answer is not known.
is_integer(n)
#> [1] TRUE
is_positive(p + 1)
#> [1] TRUE
is_real(x)
#> [1] NA
is_even(2 * n)
#> [1] TRUEThe vignette on logic and sets shows the second assumptions system,
built on ask() and Q.
Building expressions
R’s arithmetic operators work on symbolic objects, and the usual
mathematical functions (sin, exp,
log, sqrt, …) accept them. The result is a
sym object: a tree whose nodes are typed (Add,
Mul, Pow, function applications, …).
Expressions are put in a canonical form as they are built, so equal
terms are combined automatically.
e <- (x + 1)^2 * y + 3 * y * (x + 1)^2
e
#> 4*y*(x + 1)^2
sym_type(e)
#> [1] "Mul"
sym_args(e)
#> [[1]]
#> 4
#>
#> [[2]]
#> y
#>
#> [[3]]
#> (x + 1)^2
free_symbols(sin(x) * exp(y))
#> [[1]]
#> x
#>
#> [[2]]
#> yExpressions are not expanded unless you ask; see the simplification
vignette for expand(), factor_sym(), and
friends.
expand((x + y)^3)
#> x^3 + 3*x^2*y + 3*x*y^2 + y^3== tests structural equality, as in SymPy. To build an
equation use Eq(); Ne(), Lt(),
Le(), Gt(), and Ge() build the
other relations.
(x + 1)^2 == x^2 + 2 * x + 1
#> [1] FALSE
expand((x + 1)^2) == x^2 + 2 * x + 1
#> [1] TRUE
Eq(x^2, 4)
#> Eq(x^2, 4)
Lt(x, 3)
#> x < 3Undefined functions are created with Function(). They
stay unevaluated and are useful in differential equations.
Exact numbers
symcompR keeps numbers exact. Integers have arbitrary size and rationals never lose precision.
Integer(2)^100
#> 1267650600228229401496703205376
Rational(1, 3) + Rational(1, 6)
#> 1/2
Integer("123456789012345678901234567890") * 3
#> 370370367037037036703703703670
sym_factorial(Integer(25))
#> 15511210043330985984000000R evaluates 1/3 as a double before symcompR sees it, so
the result is inexact. Write Rational(1, 3), or make one
operand symbolic first with S() (an alias of
as_sym()), and the division stays exact.
x + 1/3
#> x + 0.333333333333333
x + Rational(1, 3)
#> x + 1/3
S(1) / 3
#> 1/3
sqrt(S(8))
#> 2*sqrt(2)The same applies to functions of plain R numbers:
sqrt(8) and sin(pi/6) are computed by base R,
while sqrt(S(8)) and sin(sym_pi/6) are
symbolic.
Floating point numbers are arbitrary precision Floats,
as in SymPy.
Float("1.5", 30)
#> 1.50000000000000000000000000000
x / 2 + 0.5
#> x/2 + 0.5Constants
Constants whose names would clash with R carry a sym_
prefix: sym_pi, sym_E, and sym_I
(the imaginary unit). Infinity is oo, complex infinity is
zoo, and “not a number” is nan.
EulerGamma, Catalan, and
GoldenRatio are also available.
The sym_ prefix convention
Attaching symcompR masks no base R function. SymPy functions whose
names clash with base R carry a sym_ prefix:
sym_factor(), sym_integrate(),
sym_symbols(), sym_var(),
sym_det(), sym_factorial(),
sym_binomial(), sym_beta(),
sym_Mod(), sym_trace(), and a few others.
Where base R has a generic (diff, sin,
exp, t, solve, …), symcompR adds
an S3 method instead, so the base name works on symbolic input. A few
functions also have a second name with the suffix _sym,
such as factor_sym().
sym_factor(x^3 - x)
#> x*(x - 1)*(x + 1)
factor_sym(x^3 - x)
#> x*(x - 1)*(x + 1)
sym_binomial(x, 2)
#> binomial(x, 2)
expand_func(sym_binomial(x, 2))
#> x*(x - 1)/2
sym_Mod(x + 5, 2)
#> Mod(x + 1, 2)
Integer(17) %% 5
#> 2Base R behavior is untouched for ordinary R values:
diff(c(1, 4, 9, 16))
#> [1] 3 5 7
sym_factorial(5)
#> 120Printing
A sym object prints with SymPy’s str()
form, with powers shown as ^. The printers return
strings:
-
sstr()gives the same one line form asprint(). -
srepr()shows the full expression tree. -
latex()gives LaTeX. -
pprint()draws a two dimensional picture in the console.
e <- x^2 / (y + 1) + sqrt(x)
sstr(e)
#> [1] "sqrt(x) + x^2/(y + 1)"
srepr(x^2 + 1)
#> [1] "Add(Integer(1), Pow(Symbol('x'), Integer(2)))"
latex(e)
#> [1] "\\sqrt{x} + \\frac{x^{2}}{y + 1}"
pprint(e, use_unicode = FALSE)
#> 2
#> ___ x
#> \/ x + -----
#> y + 1
pprint(Rational(1, 3) * x^3 + exp(-x))
#> 3
#> x -x
#> ── + ℯ
#> 3The printing vignette covers MathML, tables, and code generation for C, Fortran, Python, Julia, and other languages.
Substitution
subs() replaces a subexpression and simplifies the
result. It takes either an old and a new value, or a list of pairs.
e <- x^2 + y
subs(e, x, 2)
#> y + 4
subs(e, list(list(x, 2), list(y, 3)))
#> 7
subs(sin(x), x, y^2)
#> sin(y^2)
subs(x^4 + x^2, x^2, y)
#> y^2 + yxreplace() does exact structural replacement without any
mathematical matching. It takes a named list from symbol names to new
values.
Numerical evaluation
N() (also available as evalf()) evaluates
an expression to a floating point number with any number of significant
digits. The default is 15.
N(sym_pi)
#> 3.14159265358979
N(sym_pi, 50)
#> 3.1415926535897932384626433832795028841971693993751
N(sqrt(S(2)), 30)
#> 1.41421356237309504880168872421
N(exp(sym_pi * sqrt(S(163))), 40)
#> 262537412640768743.9999999999992500725972The last result is famous: e^{\pi\sqrt{163}} is within 10^{-12} of an integer, which only shows at
high precision. N() can substitute values before
evaluating, and leaves remaining symbols alone.
N(sin(x), subs = list(x = 1))
#> 0.841470984807897
N(x^2 + sym_pi, 10)
#> x^2 + 3.141592654
evalf(sqrt(S(2)) * x, 5)
#> 1.4142*xTo get an ordinary R number, use as.numeric().
as.numeric(sqrt(S(2)) + 1)
#> [1] 2.414214From expressions to R functions
lambdify() compiles an expression into a vectorized R
function, which is the fast way to evaluate an expression many times, to
plot it, or to pass it to an optimizer.
g <- lambdify(x, sin(x)^2 + cos(x))
g(c(0, 1, 2))
#> [1] 1.000000 1.248376 0.410675
h <- lambdify(list(x, y), x * y + 1)
h(1:3, 2)
#> [1] 3 5 7
body(h)
#> 1 + x * yFor example, the derivative of an expression can be handed to
uniroot():
Strings and parsing
sympify() turns a string into an expression. It accepts
both Python’s ** and R’s ^ for powers.
parse_expr(), parse_latex(), and
parse_mathematica() are described in the printing, code
generation, and parsing vignette.
Where to go next
Core algebra:
-
vignette("expressions"): traversing, substituting, and constructing expression trees. -
vignette("simplification"): expansion, factoring, and simplification. -
vignette("assumptions"): assumptions on symbols,ask(), andrefine(). -
vignette("pattern-matching"): pattern matching, unification, and rewriting strategies. -
vignette("polynomials"): polynomial algebra. -
vignette("polynomial-domains"): coefficient domains and polynomial rings. -
vignette("matrices"): linear algebra and matrix expressions. -
vignette("logic-and-sets"): Boolean algebra, sets, and ordinals.
Calculus and equations:
-
vignette("calculus"): derivatives, limits, series, sums, and products. -
vignette("integration"): integrals and integral transforms. -
vignette("series-and-sequences"): sequences, Fourier series, and formal power series. -
vignette("holonomic"): holonomic functions. -
vignette("special-functions"): special functions andPiecewise. -
vignette("solvers"): algebraic, differential, and Diophantine equations.
Discrete mathematics and algebra:
-
vignette("number-theory"): primes, factorization, and modular arithmetic. -
vignette("combinatorics"): partitions, subsets, Gray codes, and other combinatorial objects. -
vignette("permutation-groups"): permutations, permutation groups, and polyhedra. -
vignette("fp-groups"): free groups and finitely presented groups. -
vignette("galois-number-fields"): Galois groups and algebraic number fields. -
vignette("lie-algebras"): root systems and Weyl groups. -
vignette("categories"): categories and commutative diagrams. -
vignette("cryptography"): classical ciphers and key exchange.
Geometry and physics:
-
vignette("geometry"): points, lines, conics, polygons, and quaternions. -
vignette("vector-calculus"): vector calculus withCoordSys3D. -
vignette("tensors"): arrays, index notation, and tensor canonicalization. -
vignette("differential-geometry"): manifolds, fields, and forms. -
vignette("physics-units"): physical units and dimensions.
Input, output, and utilities:
-
vignette("printing"): string, pretty, LaTeX, and MathML output. -
vignette("code-printers"): code generation for other languages. -
vignette("parsing"): parsing strings, LaTeX, and Mathematica input. -
vignette("other-modules"): statistics, discrete transforms, plotting, and utilities. -
vignette("aliases-and-conditions"): alternative names and error conditions.