Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can sympy determine if expression is positive?

Tags:

python

sympy

Consider the following example:

import sympy
x = sympy.Symbol(x, real=True)
expr = sympy.sin(x) + 1

can Sympy somehow determine that expr >= 0 is always true?

like image 974
PeterE Avatar asked Mar 17 '15 17:03

PeterE


People also ask

How do you evaluate an expression in SymPy?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .

How do you compare two expressions in Python?

To test if two things are equal, it is best to recall the basic fact that if a=b, then a−b=0. Thus, the best way to check if a=b is to take a−b and simplify it, and see if it goes to 0. We will learn later that the function to do this is called simplify .

What is SymPy expression?

The Power of Symbolic Computation The real power of a symbolic computation system such as SymPy is the ability to do all sorts of computations symbolically. SymPy can simplify expressions, compute derivatives, integrals, and limits, solve equations, work with matrices, and much, much more, and do it all symbolically.

How do you substitute values in SymPy?

The subs() function in SymPy replaces all occurrences of first parameter with second. This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.


2 Answers

You could try solving the inequality for x:

>>> from sympy.solvers.inequalities import solve_univariate_inequality
>>> solve_univariate_inequality(expr >= 0, x)
And(-oo < x, x < oo)

So here SymPy tells you that the inequality holds true for any real number.

like image 138
Alex Riley Avatar answered Sep 25 '22 18:09

Alex Riley


You can also use the assumption system to inquire about the attributes of an expression. There was a recent question about this here wherein Nair gives some good references. But for your case, simply try

>>> from sympy import *
>>> var('x', real=True)
x
>>> (sin(x)+1).is_positive
>>> (sin(x)+1).is_nonnegative

The result will either be True, False or (in this case) None. None means either that the result is unknown or that the determination has not been implemented. In this case, the result for nonnegative should have been True. Improving the assumptions system is an active work with SymPy.

like image 22
smichr Avatar answered Sep 22 '22 18:09

smichr