SymPy: character / variable limit per interval

Using SymPy, is it possible to limit the possible values โ€‹โ€‹of a symbol / variable to a specific range? Now I can set some properties when defining characters, for example positive=True , but I need more control, i.e. I need to set it in the interval [0,1]. This assumption should then be used to solve, simplify, etc.

+6
source share
4 answers

You can specify boundaries as inequalities, such as x >= lb and x <= ub , for example:

 from sympy.solvers import solve from sympy import Symbol x = Symbol('x') solve([x >= 0.5, x <= 3, x**2 - 1], x) 

Here we are looking for a solution to the equation x**2 == 1 such that x is in the range [0.5, 3] .

+5
source

As for simplification, you want refine . Unfortunately, it does not yet support the use of inequality syntax, so you will have to use Q.positive or Q.negative (or Q.nonpositive or Q.nonnegative for non-strict inequalities). The most common simplification that it handles is sqrt(x**2) = x if x >= 0 .

 >>> refine(sqrt((x - 1)**2), Q.positive(x - 1)) x - 1 >>> refine(sqrt((x - 1)**2), Q.positive(x)) Abs(x - 1) 

Note that in the second case, you still get a simpler answer, because it at least knows that x - 1 is real under the given assumptions.

If your assumptions are as simple as โ€œ x positiveโ€ or โ€œ x negative,โ€ the best chance of success is to identify it on the symbol itself, for example

 >>> Symbol('x', positive=True) >>> sqrt(x**2) x 
+4
source

Now you can use solveset

In [3]: solveset(x**2 - 1, x, Interval(0.5, 3)) Out[3]: {1}

+2
source

In sympy 1.1.1, I found this to work. It can be easily adapted to your business.

 >>> x = Symbol('x', domain=S.Reals) >>> solve_domain = And(0 <= x, x < 2*pi).as_set() >>> solve_domain [0, 2โ‹…ฯ€) # solve_domain must be evaluated before solveset call >>> solveset(sin(x), x, solve_domain) {0, ฯ€} 

I donโ€™t know why things fall apart unless you evaluate solve_domain before calling solveset, but itโ€™s easy for you to work as soon as you know.

0
source

Source: https://habr.com/ru/post/956598/


All Articles