简体   繁体   中英

Solving list of expressions in sympy

I have list of expression in the form.

f1 = q1 * f2 + r1
f2 = q2 * r1 + r2
r1 = q3 * r2 + r3
r2 = q4 * r3 + r4

I would like to express r4 in terms of f1 , f2 and qn (ie q1, q2, ...). How can i perform this operation in sympy?

sympy.solve can be passed a list of expressions (equal to zero) and a list of Symbols to be solved for. If there is a solution, it is returned in a dict. Since you seek a solution in terms of the f s and q s, solve for all of the r variables.

f1, f2, r1, r2, r3, r4, q1, q2, q3, q4 = sy.symbols('f1,f2,r1,r2,r3,r4,q1,q2,q3,q4')
ans = sy.solve([
    f1 - q1 * f2 - r1,
    f2 - q2 * r1 - r2,
    r1 - q3 * r2 - r3,
    r2 - q4 * r3 - r4], [r4, r3, r2, r1])
print(ans[r4])

prints

f2*(q3*q4 + 1) - (f1 - f2*q1)*(q2*q3*q4 + q2 + q4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM