Skip to content


Mathy includes what's called a Computer Algebra System (or CAS). Its job is to turn text into math trees that can be examined and manipulated by way of a two-step process:

  1. Tokenize the text into a list of type/value pairs
  2. Parse the token list into an Expression tree



To get a sense of how Mathy's CAS components work, let's add some numbers together and assert that the result is what we think it should be.

Open Example In Colab

from mathy_core import ExpressionParser

expression = ExpressionParser().parse("4 + 2")
assert expression.evaluate() == 6

Variables Evaluation

Mathy can also deal with expressions that have variables.

When an expression has variables in it, you can evaluate it by providing the "context" to use:

Open Example In Colab

from mathy_core import ExpressionParser, MathExpression

expression: MathExpression = ExpressionParser().parse("4x + 2y")
assert expression.evaluate({"x": 2, "y": 5}) == 18

Tree Transformations

Mathy can also transform the parsed Expression trees using a set of rules that change the tree structure without altering the value it outputs when you call evaluate().

Open Example In Colab

from mathy_core import ExpressionParser
from mathy_core.rules import DistributiveFactorOutRule

input = "4x + 2x"
output = "(4 + 2) * x"
parser = ExpressionParser()

input_exp = parser.parse(input)
output_exp = parser.parse(output)

# Verify that the rule transforms the tree as expected
change = DistributiveFactorOutRule().apply_to(input_exp)
assert str(change.result) == output

# Verify that both trees evaluate to the same value
ctx = {"x": 3}
assert input_exp.evaluate(ctx) == output_exp.evaluate(ctx)

Last update: November 22, 2020