简体   繁体   中英

how to use python sympy to solve for 3 unknowns with 3 equations

i have 3 equations:

165 ⋅ 2 ⋅ 𝑦1 = 0.310 ⋅ 2 ⋅ 𝑛 + 0.517 ⋅ 2 ⋅ 𝑛

165 ⋅ 𝑦2 = 0.173 ⋅ 𝑛 + 0.517 ⋅ 𝑛

𝑦1 + 𝑦2 = 1.0

I reorganized the first 2 equations to equal Y1 and Y2 then entered them into python:

import sympy as sp

n,Y1,Y2 = sp.symbols('n Y1 Y2')
Y1= ((.310*2*n)+(.517*2*n))/(165*2)
Y2= ((.173*n)+(.517*n))/(165)
print ("Y1=", Y1,"Y2=", Y2,"n=", n)

my first question is did I set up the code right? or should I move the Y variables to the right side of the equation and label them as equation 1 and 2?

secondly, while I tried entering the 3rd equation but got a "syntax error: can't assign to operator". how would I incorporate the 3rd equation within the code? would it act more like a "limit" (I know it's not a limit but I can't think of what its called at the moment)

You can pass all three equations simultaneously and get the three variables directly using solve as following: Pass the three equations where in Eq you write the left hand side of the equation and the right hand side of the equation (or vice versa). The second argument of solve is the list of variables to be solved.

from sympy import *

n, Y1, Y2 = symbols('n Y1 Y2')
solve([Eq(((.310*2*n)+(.517*2*n))/(165*2), Y1), Eq(((.173*n)+(.517*n))/165, Y2), 
      Eq(Y1+Y2, 1)], [n, Y1, Y2])

> {n: 108.767303889255, Y1: 0.545154911008569, Y2: 0.454845088991430} # Answer

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