# Python symbolic math libraries

Python symbolic math libraries manipulate mathematical expressions as symbols rather than as floating-point numbers. A computer algebra system simplifies, differentiates, and solves expressions before code generation turns the result into numerical functions. These libraries let engineers, researchers, and AI agents derive and check mathematical models in code.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [SymPy](#sympy) | 169.9M | 15.1K | Apr 2025 | BSD |
| [Z3](#zthree-solver) | 8.2M | 13.0K | Nov 2026 | MIT |
| [CVXPY](#cvxpy) | 5.3M | 6.4K | Sep 2026 | Apache-2.0 |
| [CasADi](#casadi) | 4.1M | 2.3K | Oct 2026 | LGPL-3.0-or-later |
| [PyTensor](#pytensor) | 1.5M | 654 | Nov 2026 | BSD-3-Clause |
| [Pyomo](#pyomo) | 1.2M | 2.6K | Jun 2026 | BSD-3-Clause |
| [SymEngine](#symengine) | 365.8K | 189 | Oct 2026 | MIT |
| [pySMT](#pysmt) | 47.9K | 641 | Jun 2024 | Apache-2.0 |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[SymPy](#sympy) has the most monthly downloads in this comparison, at 169.9M.

## Capabilities

| Library | Symbolic derivative expressions | Symbolic antiderivatives | DCP rule checks | Bit-vector SMT queries |
| --- | --- | --- | --- | --- |
| [SymPy](#sympy) | Yes | Yes | No | No |
| [Z3](#zthree-solver) | No | No | No | Yes |
| [CVXPY](#cvxpy) | No | No | Yes | No |
| [CasADi](#casadi) | Yes | No | No | No |
| [PyTensor](#pytensor) | Yes | No | No | No |
| [Pyomo](#pyomo) | Yes | No | No | No |
| [SymEngine](#symengine) | Yes | No | No | No |
| [pySMT](#pysmt) | No | No | No | Via plugin |

## Libraries

### SymPy

[GitHub](https://github.com/sympy/sympy) · [PyPI](https://pypi.org/project/sympy) · [Docs](https://docs.sympy.org/latest/modules/matrices/matrices.html)

Performs symbolic calculus, equation solving, and expression manipulation.

- Downloads / mo: 169.9M
- Stars: 15.1K
- Last release: 1.14.0
- License: BSD
- Capabilities: [From the SymPy docs](https://docs.sympy.org/latest/modules/matrices/matrices.html)

**Strengths**

- **Handles symbolic calculus.** Compute derivatives, integrals, limits, and series expansions.
- **Generates code for numerical use.** Generate source code for later compilation or inclusion in another project.

**Watch out for**

- **Assumptions control simplification.** Declare positive or real symbols when those properties justify a simplification.
- **lambdify needs trusted expressions.** Keep unsanitized input out of lambdify.

```sh
pip install sympy
```

**strands-agents/tools** (1.3K stars)

[strands-agents/tools](https://github.com/strands-agents/tools) 

```python
def calculate_derivative(expr: Any, var: str, order: int) -> Any:
    """Calculate derivative of expression."""

    try:
        # Check for undefined expressions like 1/0 before attempting differentiation
        try:
            # Try to evaluate the expression to check if it's valid
            test_value = expr.evalf()
            if test_value.has(sp.zoo) or test_value.has(sp.oo) or test_value.has(-sp.oo) or test_value.has(sp.nan):
                raise ValueError(f"Cannot differentiate an undefined expression: {expr}") from None
        except (sp.SympifyError, TypeError, ZeroDivisionError):
            # If evaluation fails, the expression might be undefined
            raise ValueError(f"Cannot differentiate an undefined expression: {expr}") from None

        var_sym = sp.Symbol(var)
        return sp.diff(expr, var_sym, order)
    except Exception as e:
        raise ValueError(f"Differentiation error: {str(e)}") from e

```

[src/strands_tools/calculator.py](https://github.com/strands-agents/tools/blob/b03a6183cb3340a9091fc801965e435d5cce2cc4/src/strands_tools/calculator.py#L725-L742) · [More projects using SymPy →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20sympy%20for%20symbolic%20expressions%20differentiation%20and%20numerical%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from sympy import symbols, diff, cos

x = symbols('x')
derivative = diff(cos(x), x)

```

From [intro.html](https://docs.sympy.org/latest/tutorials/intro-tutorial/calculus.html)

### Z3

[GitHub](https://github.com/Z3Prover/z3) · [PyPI](https://pypi.org/project/z3-solver) · [Docs](https://pypi.org/project/z3-solver/)

Solves SMT problems.

- Downloads / mo: 8.2M
- Stars: 13.0K
- Last release: 5.4.1.0
- License: MIT
- Capabilities: [From the Z3 docs](https://pypi.org/project/z3-solver/)

```sh
pip install z3-solver
```

**pysmt/pysmt** (641 stars)

[pysmt/pysmt](https://github.com/pysmt/pysmt) 

```python
@clear_pending_pop
def _solve(self, assumptions: Optional[List[FNode]]=None) -> bool:
    if assumptions is not None:
        bool_ass = []
        other_ass = []
        for x in assumptions:
            if x.is_literal():
                bool_ass.append(self.converter.convert(x))
            else:
                other_ass.append(x)

        # maps the fresh literal standing for each non-literal assumption to it
        self._assumption_keys = {}
        if len(other_ass) > 0:
            self.push()
            for x in other_ass:
                key = self.mgr.FreshSymbol(template="_assumption_%d")
                self._assumption_keys[key] = x
                self.z3.add(self.converter.convert(self.mgr.Implies(key, x)))
                bool_ass.append(self.converter.convert(key))
            self.pending_pop = True
        res = self.z3.check(*bool_ass)
    else:
        res = self.z3.check()

    sres = str(res)
    assert sres in ['unknown', 'sat', 'unsat']
    if sres == 'unknown':
        raise SolverReturnedUnknownResultError
    return (sres == 'sat')

```

[pysmt/solvers/z3.py](https://github.com/pysmt/pysmt/blob/ceb8bc6d956f7ad668b733b4a9ab79465c2d7b98/pysmt/solvers/z3.py#L211-L240) · [More projects using Z3 →](https://dashboard.exa.ai/playground/search?q=z3-solver%20GitHub%20projects)

**Quickstart**

```python
from z3 import Real, simplify

x = Real('x')
expression = simplify(x + 0)

```

From [README.md](https://github.com/Z3Prover/z3/blob/master/src/api/python/z3/z3.py)

### CVXPY

[GitHub](https://github.com/cvxpy/cvxpy) · [PyPI](https://pypi.org/project/cvxpy) · [Docs](https://pypi.org/project/cvxpy/)

Models convex optimization problems in Python.

- Downloads / mo: 5.3M
- Stars: 6.4K
- Last release: 1.9.3
- License: Apache-2.0
- Capabilities: [From the CVXPY docs](https://pypi.org/project/cvxpy/)

```sh
pip install cvxpy
```

**cvxgrp/dccp** (136 stars)

[cvxgrp/dccp](https://github.com/cvxgrp/dccp) 

```python
def convexify_obj(
    obj: cp.Minimize | cp.Maximize,
    linearization_map: dict[int, LinearizationData] | None = None,
) -> cp.Minimize | None:
    """Convexify an objective function for DCCP problems.

    Linearize non-DCP objectives. If the objective is already DCP, returns it unchanged.
    If the objective is a maximization problem, it is negated to convert it into a
    minimization problem.

    Parameters
    ----------
    obj : cp.Minimize | cp.Maximize
        Objective of a problem to be convexified.
    linearization_map : dict, optional
        Map for caching linearization parameters.

    Returns
    -------
    cp.Minimize or None
        Convexified objective if linearization is possible, None otherwise.

    """
    # negate the objective if it is a maximization problem
    expr = obj.expr
    if isinstance(obj, cp.Maximize):
        expr = -expr
    if obj.is_dcp():
        logger.debug("Objective is already DCP.")
        return cp.Minimize(expr)

    # linearize the objective expression. If it fails, the gradient is not defined
    lin = linearize(expr, linearization_map)
    if lin is not None:
        return cp.Minimize(lin)
    return None

```

[src/dccp/objective.py](https://github.com/cvxgrp/dccp/blob/13fbee1ecb696a9860d87af57a3eb80a5067902b/src/dccp/objective.py#L12-L47) · [More projects using CVXPY →](https://dashboard.exa.ai/playground/search?q=cvxpy%20GitHub%20projects)

**Quickstart**

```python
from cvxpy import Variable
from cvxpy.transforms import linearize

x = Variable()
x.value = 2.0
tangent = linearize(x ** 2)

```

From [cvxpy.transforms.html](https://www.cvxpy.org/api_reference/cvxpy.transforms.html)

### CasADi

[GitHub](https://github.com/casadi/casadi) · [PyPI](https://pypi.org/project/casadi) · [Docs](http://docs.casadi.org)

Builds symbolic models with automatic differentiation for numerical optimization.

- Downloads / mo: 4.1M
- Stars: 2.3K
- Last release: 3.8.2
- License: LGPL-3.0-or-later
- Capabilities: [From the CasADi docs](http://docs.casadi.org)

**Strengths**

- **Computes model derivatives.** Build Jacobians and gradients from symbolic model expressions.
- **Generates self-contained C code.** Export supported function objects as C code.

**Watch out for**

- **Existing models need CasADi syntax.** Reimplement existing models with CasADi expressions before using its differentiation tools.
- **Algebraic manipulation is limited.** Choose a computer algebra system for broader symbolic expression manipulation.

```sh
pip install casadi
```

**opencap-org/opencap-processing** (163 stars)

[opencap-org/opencap-processing](https://github.com/opencap-org/opencap-processing) 

```python
def generateF(dim, script_name):
    foo_module = importlib.import_module(script_name)
    importlib.reload(foo_module)
    cg = ca.CodeGenerator('foo_jac')
    arg = ca.SX.sym('arg', dim)
    y,_,_ = foo_module.foo(arg)
    F = ca.Function('F',[arg],[y])
    cg.add(F)
    cg.add(F.jacobian())
    cg.generate()

```

[UtilsDynamicSimulations/OpenSimAD/utilsOpenSimAD.py](https://github.com/opencap-org/opencap-processing/blob/72b5416bf6172fe3d9b42b01e1a02252362b20fc/UtilsDynamicSimulations/OpenSimAD/utilsOpenSimAD.py#L1661-L1670) · [More projects using CasADi →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20casadi%20for%20symbolic%20expressions%20differentiation%20and%20numerical%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import casadi as ca

x = ca.SX.sym('x')
derivative = ca.jacobian(ca.sin(x), x)

```

From [docs.md](https://web.casadi.org/docs/)

### PyTensor

[GitHub](https://github.com/pymc-devs/pytensor) · [PyPI](https://pypi.org/project/pytensor) · [Docs](https://pytensor.readthedocs.io/en/latest/)

Compiles mathematical expressions for evaluation on CPUs and GPUs.

- Downloads / mo: 1.5M
- Stars: 654
- Last release: 3.3.8
- License: BSD-3-Clause
- Capabilities: [From the PyTensor docs](https://pytensor.readthedocs.io/en/latest/)

```sh
pip install pytensor
```

**Quickstart**

```python
import pytensor
import pytensor.tensor as pt

x = pt.dscalar('x')
derivative = pt.grad(x ** 2, x)
evaluate = pytensor.function([x], derivative)
value = evaluate(3.0)

```

From [gradients.html](https://pytensor.readthedocs.io/en/latest/tutorial/gradients.html) · [Find projects using PyTensor →](https://dashboard.exa.ai/playground/search?q=pytensor%20GitHub%20projects)

### Pyomo

[GitHub](https://github.com/Pyomo/pyomo) · [PyPI](https://pypi.org/project/pyomo) · [Docs](https://pyomo.readthedocs.io/en/stable/)

Models optimization problems.

- Downloads / mo: 1.2M
- Stars: 2.6K
- Last release: 6.10.1
- License: BSD-3-Clause
- Capabilities: [From the Pyomo docs](https://pyomo.readthedocs.io/en/stable/)

```sh
pip install pyomo
```

**Quickstart**

```python
from pyomo.environ import ConcreteModel, Var
from pyomo.core.expr.calculus.derivatives import differentiate, Modes

model = ConcreteModel()
model.x = Var(initialize=2)
derivative = differentiate(model.x ** 2, wrt=model.x, mode=Modes.reverse_symbolic)

```

From [pyomo.core.expr.calculus.derivatives.differentiate.html](https://pyomo.readthedocs.io/en/stable/api/pyomo.core.expr.calculus.derivatives.differentiate.html) · [Find projects using Pyomo →](https://dashboard.exa.ai/playground/search?q=pyomo%20GitHub%20projects)

### SymEngine

[GitHub](https://github.com/symengine/symengine.py) · [PyPI](https://pypi.org/project/symengine) · [Docs](https://symengine.org/symengine.py)

Exposes the C++ SymEngine symbolic manipulation library to Python.

- Downloads / mo: 365.8K
- Stars: 189
- Last release: 0.15.0
- License: MIT
- Capabilities: [From the SymEngine docs](https://symengine.org/symengine.py)

**Strengths**

- **Creates numerical callbacks.** Turn symbolic expressions into callbacks accepting real or complex numerical inputs.
- **Expands symbolic expressions.** Build expressions with symbols and expand their products.

**Watch out for**

- **LLVM needs a compatible build.** Select the LLVM backend only in builds compiled with LLVM support.
- **Source builds need matching core.** Use the supported SymEngine core revision when building the Python wrapper.

```sh
pip install symengine
```

**Quickstart**

```python
from symengine import Symbol

x, y = Symbol('x'), Symbol('y')
expanded = ((x + y) ** 2).expand()

```

From [README.md](https://github.com/symengine/symengine.py/blob/main/README.md) · [Find projects using SymEngine →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20symengine%20for%20symbolic%20expressions%20differentiation%20and%20numerical%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

### pySMT

[GitHub](https://github.com/pysmt/pysmt) · [PyPI](https://pypi.org/project/pysmt) · [Docs](https://pypi.org/project/pysmt/)

Manipulates and solves SMT formulas across solvers.

- Downloads / mo: 47.9K
- Stars: 641
- Last release: 0.9.6
- License: Apache-2.0
- Capabilities: [From the pySMT docs](https://pypi.org/project/pysmt/)

```sh
pip install pysmt
```

**riscv/riscv-crypto** (413 stars)

[riscv/riscv-crypto](https://github.com/riscv/riscv-crypto) 

```python
def overlaps(i,j):
    """
    Returns True if two instructions i,j overlap in their encoding.

    TODO: Add operand constraints into the solver formula.
    """
    if(i.pseudo or j.pseudo):
        return False
    ILEN=32

    instr   = Symbol("instr"    , BVType(width=ILEN))
    imask   = Symbol("imask"    , BVType(width=ILEN))
    imatch  = Symbol("imatch"   , BVType(width=ILEN))
    jmask   = Symbol("jmask"    , BVType(width=ILEN))
    jmatch  = Symbol("jmatch"   , BVType(width=ILEN))

    domains = And([
        EQ(imask , BV(i.mask() ,width=ILEN)),
        EQ(imatch, BV(i.match(),width=ILEN)),
        EQ(jmask , BV(j.mask() ,width=ILEN)),
        EQ(jmatch, BV(j.match(),width=ILEN))
    ])

    problem = And([
        EQ(instr & imask, imatch),
        EQ(instr & jmask, jmatch)
    ])

    formula = And(domains, problem)

    return is_sat(formula)

```

[bin/better_parse_opcodes.py](https://github.com/riscv/riscv-crypto/blob/9cb90879050f68de8ba0b2f8bc34bec599ac8025/bin/better_parse_opcodes.py#L298-L328) · [More projects using pySMT →](https://dashboard.exa.ai/playground/search?q=pysmt%20GitHub%20projects)

**Quickstart**

```python
from pysmt.shortcuts import Symbol, Int, Plus, simplify
from pysmt.typing import INT

x = Symbol('x', INT)
expression = simplify(Plus(x, Int(0)))

```

From [shortcuts.py](https://github.com/pysmt/pysmt/blob/29bdb9c363e3f4a953dac73e908a45571db7623f/pysmt/shortcuts.py)

## FAQ

### Which Python symbolic math library should I use?

[SymPy](#sympy) suits general computer algebra, symbolic calculus, and equation solving. [CVXPY](#cvxpy) and [Pyomo](#pyomo) suit optimization models. [Z3](#zthree-solver) suits satisfiability problems over arithmetic, Boolean, and bit-vector expressions. [CasADi](#casadi) suits numerical optimization that needs automatic derivatives.

### What is SymPy?

[SymPy](#sympy) is a computer algebra system in Python for symbolic calculus, equation solving, and expression manipulation. It also generates code for numerical use.

### What is CVXPY?

[CVXPY](#cvxpy) is a domain-specific language for modeling convex optimization problems in Python.

### What is Pyomo?

[Pyomo](#pyomo) is an optimization modeling framework with algebraic modeling expressions and interfaces to solvers.

### What is CasADi?

[CasADi](#casadi) builds symbolic models with automatic differentiation for numerical optimization and generates self-contained C code. Existing models must be rewritten in CasADi syntax.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python symbolic math libraries SymPy SymEngine CasADi Pymbolic code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
