解决 Python 中 6 个非线性方程组的问题

Trouble solving a system of 6 nonlinear equations in Python

我正在尝试用 Python 求解 6 个非线性方程组。到目前为止我有:

from scipy.optimize import fsolve 
import math 
from numpy import log

ka1 = 1.045
ka2 = 0.1759
ka3 = 0.3159

def equations(p):
    yh2o, yco2, yh2, ych4, yco = p

    return (yh2o + yco2 + yh2 + ych4 + yco - 1,
        ka1 - (yh2o ** 2)/(yco * (yh2 ** 2),
        ka2 - (yco ** 2) / yco2,
        ka3 - ych4 / (yh2 ** 2),
        0.5 - (2.0 * yco2 + yco + yh2o) / (2 * yh2o + 2 * yh2 + 4 * ych4)))

yh2o, yco2, yh2, ych4, yco = fsolve(equations, [0.2, 0.2, 0.2, 0.2, 0.2])

print(f"yh2o = {yh2o}, yco2 = {yco2}, yh2 = {yh2}, ych4 = {ych4}, yco = {yco}")

当我尝试 运行 这个时,我得到

TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument 'equations'.Shape should be (5,) but it is (2,).

我试过改变最初的猜测,但错误还是一样。

我也试过将方程式变成多项式,如下所示:

    return (yh2o + yco2 + yh2 + ych4 + yco - 1.0,
        ka1 * (yco * (yh2 ** 2.0)) - (yh2o * yh2o),
        ka2 * (yco2) - (yco ** 2.0),
        ka3 * (yh2 ** 2.0) - ych4,
        0.5 * (2.0 * yh2o + 2.0 * yh2 + 4 * ych4) - (2.0 * yco2 + yco + yh2o)) 

但我收到一条错误消息

TypeError: can't multiply sequence by non-int of type 'float'

我认为您只是在方程式(返回的元组)中使用括号(即放置 ())有问题。

以下是完整更正的工作代码:

Try it online!

from scipy.optimize import fsolve 
import math 
from numpy import log

ka1 = 1.045
ka2 = 0.1759
ka3 = 0.3159

def equations(p):
    yh2o, yco2, yh2, ych4, yco = p

    return (
        (yh2o + yco2 + yh2 + ych4 + yco - 1),
        ka1 - (yh2o ** 2) / (yco * (yh2 ** 2)),
        ka2 - (yco ** 2) / yco2,
        ka3 - ych4 / (yh2 ** 2),
        0.5 - (2.0 * yco2 + yco + yh2o) / (2 * yh2o + 2 * yh2 + 4 * ych4)
    )

yh2o, yco2, yh2, ych4, yco = fsolve(equations, [0.2, 0.2, 0.2, 0.2, 0.2])

print(f"yh2o = {yh2o}, yco2 = {yco2}, yh2 = {yh2}, ych4 = {ych4}, yco = {yco}")

输出:

yh2o = 0.17829101808889491, yco2 = 0.17513942402710805, yh2 = 0.4163023675952086, ych4 = 0.05474789024926531, yco = 0.1755193000395232