如何在 python 中数值求解超定非线性方程组?

问题描述 投票:0回答:1

我正在尝试求解具有两个变量的 4 个指数方程组。但是,如果我使用 fsolve,python 将只允许我两个使用与我有变量一样多的方程式。但是由于我有无限多对解(如果只使用两个方程)并且我需要找到不仅适合两个方程而且适合所有四个方程的变量对,fsolve 似乎不起作用。

所以知道我的代码看起来像这样:

from scipy.optimize import fsolve
c_1 = w+(y/(x*R))
c_2 = offset - (c_1/(x*R)) #offset(1.05), w(10) and R(0.35) are constants 
def equations(p):
    x,y = p
    eq1 = (c_1*sp.exp(-y*R*1.017))/(y*R)+c_2-(x*1.017)/(y*R)-(5.1138*2*np.pi)
    eq2 = (c_1*sp.exp(-y*R*2.35))/(y*R)+c_2-(x*2.35)/(y*R)-(2.02457*4*np.pi)
    eq3 = (c_1*sp.exp(-y*R*2.683))/(y*R)+c_2-(x*2.683)/(y*R)-(6.0842178*4*np.pi)
    return (eq1,eq2,eq3)

x, y =  fsolve(equations, (1,1))

print (equations((x, y)))

然而,根据我给出的初始猜测,这将给我截然不同的结果。我现在想编辑这段代码,这样我就可以添加额外的方程式来保证我得到正确的 x,y 对作为解决方案。只需在函数中添加第三个等式,当然会返回 TypeError,所以我想知道如何做到这一点。

python scipy equation-solving nonlinear-equation fsolve
1个回答
0
投票

要添加任意数量的方程式,我认为您根本不能使用

fsolve
。只需运行最小二乘最小化,并确保正确矢量化而不是死记硬背。以下确实会运行并生成结果,但我尚未评估其准确性。

import numpy as np
from scipy.optimize import minimize

offset = 1.05
w = 10
R = 0.35
a = np.array((-1.017, -2.350, -2.683))
b = np.array((
    -5.1138000*2,
    -2.0245700*4,
    -6.0842178*4,
))*np.pi


def equations(x: float, y: float) -> np.ndarray:
    c_1 = w + y/x/R
    c_2 = offset - c_1/x/R

    return (c_1*np.exp(a*y*R) + a*x)/y/R + c_2 + b


def error(xy: np.ndarray) -> np.ndarray:
    eqs = equations(*xy)
    return eqs.dot(eqs)


result = minimize(
    fun=error,
    x0=(1, 1),
    method='nelder-mead',
)
print(result.message)
print('x, y =', result.x)
print('equations:', equations(*result.x))
Optimization terminated successfully.
x, y = [0.19082078 0.13493941]
equations: [ 27.4082168   13.91087443 -42.00388728]
© www.soinside.com 2019 - 2024. All rights reserved.