# Get the nth term of an equation.rhs() sum

Hi

equ0 = term_0 == term_1 + term_2 + term_3

I want to extract term_1 + term_2 to work with.

I have been looking for a long time without success, I read the whole page: link text

example: ${\left| p\left(\rho_{\epsilon} e^{\left(i \, \theta_{\epsilon}\right)} + w\right) \right|}^{2} = \rho_{0} \rho_{\epsilon}^{m} \rho_{m} e^{\left(i \, m \theta_{\epsilon} - i \, \theta_{0} + i \, \theta_{m}\right)} + \rho_{0} \rho_{\epsilon}^{m} \rho_{m} e^{\left(-i \, m \theta_{\epsilon} + i \, \theta_{0} - i \, \theta_{m}\right)} + \rho_{\epsilon}^{2 \, m} \rho_{m}^{2} + \rho_{0}^{2}$

edit retag close merge delete

Sort by » oldest newest most voted
var('term_0 term_1 term_2 term_3')
equ0 = term_0 == term_1 + term_2 + term_3

# use the operands method of expressions
print equ0.rhs().operands()

# subtract third term (the last in the list of operands)
print equ0.rhs() - equ0.rhs().operands()[-1]
# or build expression from list of operands
print sum(equ0.rhs().operands()[:2])

more

Thanks too ndomes.

( 2017-09-03 05:47:41 -0600 )edit

moreover operands() appears in the link I put above, but I did not see it ;-(, really sorry.

( 2017-09-03 05:53:42 -0600 )edit

You should really give explicit example with Sage code, so that we really understand what do you want to achieve. Let me take my own example:

sage: equ0 = cos(x) == 3*x^2 + log(x) + 42*sin(x)
sage: equ0
cos(x) == 3*x^2 + log(x) + 42*sin(x)


You can first extract the right-hand-side of the equation as follows:

sage: equ0.rhs()
3*x^2 + log(x) + 42*sin(x)


Then, you can check that it is an addition:

sage: equ0.rhs().operator()


For which you can get the operands:

sage: equ0.rhs().operands()
[3*x^2, log(x), 42*sin(x)]


You can extract the first two terms of this list:

sage: equ0.rhs().operands()[:2]
[3*x^2, log(x)]


You can them add them together:

sage: sum(equ0.rhs().operands()[:2])
3*x^2 + log(x)


WARNING the order of the operands is not necessrilly the one you entered:

sage: equ0 = cos(x) == log(x) + 3*x^2 + 42*sin(x)
sage: equ0
cos(x) == 3*x^2 + log(x) + 42*sin(x)

more

Thanks tmonteil, it is exactly what I would like to do ! you said "WARNING the order of the operands is not necessarily the one you entered"

Yes,but if it is the first term I see when I do a show(equ0.rhs()) I suppose it will have the first indice for operands().

( 2017-09-03 05:46:27 -0600 )edit

Correct, the way symbolic operands are reordered by Sage is deterministic.

( 2017-09-03 06:20:55 -0600 )edit