python-3.6sympy

Assuming a symbol is between zero and one with SymPy?


I am doing symbolic manipulation of very large expressions in Python using SymPy. Most of the symbols that I am manipulating represent nonnegative, real numbers, less than or equal to one.

How can I tell SymPy these assumptions? I have figured out that I can do the following when creating the symbol.

import sympy as sym

x = sym.symbols('x', real=True, nonnegative=True)

but I don't see how to impose the upper bound of one.


Solution

  • Unfortunately, the currently implemented system of assumptions does not provide a way to impose such a bound. For some purposes, it may be reasonable to introduce algebraic structure that implies the bound: for example,

    t = sym.symbols('t', nonnegative=True)
    x = t/(1+t)
    

    Now SymPy knows that x is between 0 and 1:

    >>> x < 1
    True
    >>> x >= 0
    True
    

    Whether this is helpful depends on how natural this substitution for the expressions you are working with. Another option is x = sym.exp(-t)