On Fri, Jun 24, 2011 at 12:42 AM, Jeff Pickhardt <[email protected]>wrote:
> Hey guys,
>
> I'm reading through the SymPy code and, well, it's somewhat overwhelming if
> you're new to the project because there's so much going on. (That's a good
> thing too - it means its robust!)
>
> Can someone help explain how this works?
>
> >>> from sympy import *
Import many of the sympy functions from all the different modules.
> >>> x = Symbol("x")
create a sympy symbol named 'x' and assign it to a python variable named
'x'
>
> >>> my_expression = sin(x)**2 + 2*sin(x) + 1
a sympy Expr is created which is an Add with 3 terms, a Pow, Mul and One
(etc...). It is assigned to a python variable named my_expression.
>
> >>> my_expression.factor()
This calls a method that factors the object associated with my_expression
(the Expr created on the rhs of the equal sign). This is where it can get
confusing because what happens "under the hood" might involve converting the
Expr to a Poly to do the work and then reconverting it to an Expr.
(integrate is an interesting routine in this regard because it does what I
-- a layman in this regard -- consider some pretty esoteric stuff to come up
with the answer.)
>
> (1 + sin(x))**2
This is the final Expr, a Pow with base that is an Add and exponent that is
an Integer.
>
> >>>
>
> For instance, what data structures happen when I create my_expression, what
> happens when I factor it, etc. A high-level walk through would help. I see
> there's stuff going on at polytools.py, and I think _symbolic_factor gets
> called. It's just confusing to keep everything in my head when I don't yet
> have a high level understanding of how sympy expressions and what not
> actually work.
>
>
You can get a feel for what you are working with by using args and srepr:
>>> 1+2*sin(x)+sin(x)**2
sin(x)**2 + 2*sin(x) + 1
>>> eq=_
>>> eq.args
(1, 2*sin(x), sin(x)**2)
>>> srepr(eq)
"Add(Pow(Function('sin')(Symbol('x')), Integer(2)), Mul(Integer(2),
Function('si
n')(Symbol('x'))), Integer(1))"
Using the preorder_traversal, you can get the same information a little at a
time:
>>> from sympy.utilities.iterables import *
>>> p = preorder_traversal(eq)
>>> for i in p:
... print i, type(i)
...
sin(x)**2 + 2*sin(x) + 1 <class 'sympy.core.add.Add'>
1 <class 'sympy.core.numbers.One'>
2*sin(x) <class 'sympy.core.mul.Mul'>
2 <class 'sympy.core.numbers.Integer'>
sin(x) sin
x <class 'sympy.core.symbol.Symbol'>
sin(x)**2 <class 'sympy.core.power.Pow'>
sin(x) sin
x <class 'sympy.core.symbol.Symbol'>
2 <class 'sympy.core.numbers.Integer'>
Hope that helps. Feel free to ask any other questions.
Chris
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sympy?hl=en.