[英]Solution to a system of non-linear equations in R^2
I am trying to find a solution to the following system where f and g are R^2 -> R^2 functions:我试图找到以下系统的解决方案,其中 f 和 g 是 R^2 -> R^2 函数:
f(x1,x2) = (y1,y2) f(x1,x2) = (y1,y2)
g(y1,y2) = (x1,x2) g(y1,y2) = (x1,x2)
I tried solving it using scipy.optimize.fsolve as follows:我尝试使用 scipy.optimize.fsolve 解决它,如下所示:
def eqm(vars):
x1,x2,y1,y2 = vars
eq1 = f([x1, x2])[0] - y1
eq2 = f([x1, x2])[1] - y2
eq3 = g([y1, y2])[0] - x1
eq4 = g([y1, y2])[1] - x2
return [eq1, eq2, eq3, eq4]
fsolve(eqm, x0 = [1,0.5,1,0.5])
Although it is returning an output, it does not seem to be a correct one as it does not seem to satisfy the two conditions, and seems to vary a lot with the x0 specified.虽然它正在返回一个输出,但它似乎不是一个正确的输出,因为它似乎不满足这两个条件,并且似乎与指定的 x0 变化很大。 Also getting a warning: 'The iteration is not making good progress, as measured by the improvement from the last ten iterations.'还收到警告:“根据最近十次迭代的改进来衡量,迭代没有取得良好的进展。” I do know for a fact that a unique solution exists, which I have obtained algebraically.我确实知道存在一个独特的解决方案,这是我通过代数获得的。
Not sure what is going on and if there is a simpler way of solving it, especially using just two equations instead of splitting up into 4. Something like:不知道发生了什么,以及是否有更简单的方法来解决它,尤其是只使用两个方程而不是分成 4 个。比如:
def equations(vars):
X,Y = vars
eq1 = f(X)-Y
eq2 = g(Y)-X
return [eq1, eq2]
fsolve(equations, x0 =[[1,0.5],[1,0.5]])
Suggestions on other modules eg sympy are also welcome!也欢迎对其他模块提出建议,例如 sympy!
First, I recommend working with numpy arrays since manipulating these is simpler than lists.首先,我建议使用 numpy 数组,因为操作这些数组比列表更简单。
I've slighlty rewritten your code:我稍微重写了你的代码:
import scipy.optimize as opt
def f(x):
return x
def g(x):
return x
def func(vars):
input = np.array(vars)
eq1 = f(input[:2]) - input[2:]
eq2 = g(input[2:]) - input[:2]
return np.concatenate([eq1, eq2])
root = opt.fsolve(func, [1, 1, 0., 1.2])
print(root)
print(func(root)) # should be close to zeros
What you have should work correctly, so I believe there is something wrong with the equations you're using.你所拥有的应该可以正常工作,所以我相信你使用的方程式有问题。 If you provide those, I can try to see what may be wrong.如果您提供这些,我可以尝试看看可能有什么问题。
This seems to be more of a problem of numerical mathematics than Python coding.这似乎更像是一个数值数学问题,而不是 Python 编码问题。 Your functions may have "ugly" behavior around the solution, may be strongly non-linear or contain singularities.您的函数在解决方案周围可能有“丑陋”的行为,可能是强烈的非线性或包含奇点。 We cannot help further without seeing the functions.如果没有看到这些功能,我们将无法提供进一步的帮助。 One thing you might try is to instead solve a system您可能会尝试的一件事是解决一个系统
g(f(x)) - x = 0 g(f(x)) - x = 0
and simplify g(f(x)) as much as possible analytically.并尽可能在解析上简化 g(f(x))。 Then calculate y = f(x) after solving the equation.然后求解方程后计算 y = f(x)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.