Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SymPy -- define domain of variable

Tags:

python

sympy

I'm writing a program to compute an exact differential for my physics laboratory. I know that I can set real domain or positive (from sympy import *):

x, y, z = symbol('x y z', positive = True)

My problem is to specify domain for example n>1. Is it possible? In my output I'm getting an expresion like |n^2-1| and with setting this domain n>1 I would accept output like n^2-1 (without absolute value "||")

like image 976
andywiecko Avatar asked Oct 19 '15 14:10

andywiecko


People also ask

How define SymPy function?

SymPy variables are objects of Symbols class. Symbol() function's argument is a string containing symbol which can be assigned to a variable. A symbol may be of more than one alphabets. SymPy also has a Symbols() function that can define multiple symbols at once.

How do you represent E in SymPy?

Note that by default in SymPy the base of the natural logarithm is E (capital E ). That is, exp(x) is the same as E**x .

How do you assign a value to a symbol in Python?

The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.


1 Answers

For assumptions on symbols, you can use positive or negative:

p = Symbol('p', positive=True)

But this can only define p>0 (or p<0 if you use negative=True).

For more complex expression refinement, try refine(expression, assumption):

In [1]: n = Symbol('n')

In [2]: refine(Abs(n-1), Q.positive(n-1))
Out[2]: n - 1

In [3]: refine(Abs(n-1))
Out[3]: │n - 1│

That is, you create the assumption Q.positive(n-1), that is n > 1, and pass it to refine.

There is currently work in progress to port this assumption style to other algorithms, but support is still incomplete (simplify appears not to recognize this kind of assumption).

It is expected that support of Q.statement( ... ) will be extended in future versions of SymPy, as there is currently a lot of work in progress on this.

like image 107
Francesco Bonazzi Avatar answered Oct 18 '22 17:10

Francesco Bonazzi