用Python解决非线性方程组(scipy.optimize.fsolve) [英] Solve a system of non-linear equations in Python (scipy.optimize.fsolve)
本文介绍了用Python解决非线性方程组(scipy.optimize.fsolve)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I am trying to solve the following simple system of non-linear equations (Source(second example)):
(I) y - x^2 = 7 - 5x
(II) 4y - 8x = -21
应该只有一个解(x = 3.5,y = 1.75).
which should have only one solution (x=3.5, y=1.75).
我当前使用 scipy 堆栈如下:
from scipy.optimize import fsolve
def equations(p):
x, y = p
return (y - x**2 -7 + 5*x, 4*y - 8*x + 21)
x, y = fsolve(equations, (5, 5))
print(equations((x, y)))
并产生以下结果(不是结果):
and yields the following (which is not the result):
(0.0, 0.0)
我已经尝试了不同的初始估计,但是它没有提供正确的解决方案.
I have already tried different starting estimates but it doesn't deliver the right solution.
我的方法有什么问题?我想念什么吗?
What's wrong with my approach? Am I missing something?
提前谢谢!
推荐答案
这工作得很好:
In [1]: %paste
from scipy.optimize import fsolve
def equations(p):
x, y = p
return (y - x**2 -7 + 5*x, 4*y - 8*x + 21)
x, y = fsolve(equations, (5, 5))
print(equations((x, y)))
## -- End pasted text --
(0.0, 0.0)
In [2]: x
Out[2]: 3.5000000414181831
In [3]: y
Out[3]: 1.7500000828363667
equations(x, y)
为(0, 0)
表示y - x**2 -7 + 5*x
和4*y - 8*x + 21
均为0.
也许您感到困惑并且打算使用print(x, y)
而不是print(equations(x, y))
吗?
Maybe you got confused and meant to print(x, y)
instead of print(equations(x, y))
?
这篇关于用Python解决非线性方程组(scipy.optimize.fsolve)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文