Hi,
On 16 April 2011 18:47, refp16 <[email protected]> wrote:
> How do I extract the nth term of an expanded polynomial that is
> ordered in a particular way (increasing exponents)?
>
> For example, from:
>
> 1 + x**3 + 2*x**9 + 2*x**12 + 3*x**27 + 3*x**30 + 6*x**36 + 6*x**39
>
> I want the 7th term.
>
> I have tried args but this gives me a tuple that is not ordered in the
> same way as its polynomial:
>
> (1, 2*x**12, 3*x**30, 6*x**36, 3*x**27, x**3, 6*x**39, 2*x**9)
>
> My polynomial is type <class 'sympy.core.add.Add'> and I built it
> using the following code:
>
> from sympy import *
> x,y,z = symbols('xyz')
>
> aux = 1 + x**3
> for n in range(2, 4):
> baseTerm = 1 + n*x**3**n
> aux = aux * baseTerm
> auxex = aux.expand()
> print auxex
>
> I also tried methods of the Poly class, but I believe they don´t work
> precisely because my polynomial is not a Poly object. Would one way be
> converting to Poly and then using those methods? How would I convert?
>
I will assume you use SymPy 0.6.7 (the procedure will be a little different
for development version of SymPy). You can extract terms of polynomials in
two ways:
In [1]: aux = 1 + x**3
In [2]: for n in range(2, 4):
...: baseTerm = 1 + n*x**3**n
...: aux = aux * baseTerm
...:
...:
In [3]: f = aux.expand()
In [4]: f
Out[4]:
3 9 12 27 30 36 39
1 + x + 2⋅x + 2⋅x + 3⋅x + 3⋅x + 6⋅x + 6⋅x
Either using coeff() method from Basic:
In [5]: f.coeff(x**12)
Out[5]: 2
In [6]: f.coeff(x**15) # this returns None, not 0
or convert `f` to an instance of Poly class and also use coeff():
In [7]: g = Poly(f, x)
In [8]: g.coeff(12)
Out[8]: 2
In [9]: g.coeff(15) # now this is really zero
Out[9]: 0
> The latter code takes me to another question: Sum is the sum operator,
> but don´t we have a product operator?
>
There are both:
In [1]: sum(k, (k, 1, n))
Out[1]:
2
n n
─ + ──
2 2
In [2]: product(k, (k, 1, n))
Out[2]: n!
In [3]: sum(k, (k, 1, 10))
Out[3]: 55
In [4]: product(k, (k, 1, 10))
Out[4]: 3628800
However, if you have to add or multiply elements of an iterable container,
then it may be simpler (and much faster) to appropriate constructors
directly:
In [5]: Add(x, y, z)
Out[5]: x + y + z
In [6]: Mul(x, y, z)
Out[6]: x⋅y⋅z
>
> Thank you.
>
> --
> 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.
>
>
Mateusz
--
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.