一些用fsolve解决非线性方程组的假设示例:
from scipy.optimize import fsolve
import math
def equations(p):
x, y = p
return (x+y**2-4, math.exp(x) + x*y - 3)
x, y = fsolve(equations, (1, 1))
print(equations((x, y)))
Run Code Online (Sandbox Code Playgroud)
是否可以使用scipy.optimize.brentq一定间隔(例如[-1,1])来解决?在这种情况下,拆包如何工作?
小智 6
正如sascha所建议的那样,约束优化是最简单的方法。该least_squares方法在这里很方便:您可以直接将equations其传递给它,它将最小化其组件的平方和。
from scipy.optimize import least_squares
res = least_squares(equations, (1, 1), bounds = ((-1, -1), (2, 2)))
Run Code Online (Sandbox Code Playgroud)
boundsis 的结构((min_first_var, min_second_var), (max_first_var, max_second_var)),或类似地用于更多变量。
结果对象具有一堆字段,如下所示。最相关的是:res.cost本质上为零,表示找到了根;并res.x说出根是什么:[0.62034453,1.83838393]
active_mask: array([0, 0])
cost: 1.1745369255773682e-16
fun: array([ -1.47918522e-08, 4.01353883e-09])
grad: array([ 5.00239352e-11, -5.18964300e-08])
jac: array([[ 1. , 3.67676787],
[ 3.69795254, 0.62034452]])
message: '`gtol` termination condition is satisfied.'
nfev: 7
njev: 7
optimality: 8.3872972696740977e-09
status: 1
success: True
x: array([ 0.62034453, 1.83838393])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2694 次 |
| 最近记录: |