Python中的多元根查找 [英] Multivariate Root Finding in Python

查看:49
本文介绍了Python中的多元根查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用excel求解器,很容易找到这个方程的解(x和y的最佳值):

Using excel solver, it is easy to find a solution (optimum value for x and y )for this equation:

(x*14.80461) + (y * -4.9233) + (10*0.4803) ≈ 0

(x*14.80461) + (y * -4.9233) + (10*0.4803) ≈ 0

但是,我不知道如何在 Python 中执行此操作.现有的 scipy 优化库函数,如 fsolve() 或 leastsq() 似乎只适用于一个变量......(我可能只是不知道如何使用它们)......

However, I can't figure out how to do this in Python. The existing scipy optimize library function like fsolve() or leastsq() seems to work with only one variable.... (I might just not know how to use them)...

有什么建议吗?

谢谢!

推荐答案

>>> def f(x):
...     return x[0]*14.80461 + x[1]*(-4.9233) + x[2]*(10*0.4803) 
>>> def vf(x):
...    return [f(x), 0, 0]
>> xx = fsolve(vf, x0=[0,0,1])
>>> 
>>> f(xx)
8.8817841970012523e-16

由于解不是唯一的,未知的不同初始值会导致不同(有效)解.

Since the solution is not unique, different initial values for an unknown lead to different (valid) solutions.

为什么这有效.嗯,这是一个肮脏的黑客.只是fsolve 和它的亲戚处理方程的系统.我在这里做了什么,我为三个变量(x 有三个元素)定义了一个由三个方程组成的系统(f(x) 返回一个三元素列表).现在 fsolve 使用牛顿型算法收敛到一个解.

Why this works. Well, it's a dirty hack. It's just that fsolve and its relatives deal with systems of equations. What I did here, I defined a system of three equations (f(x) returns a three-element list) for three variables (x has three elements). Now fsolve uses a Newton-type algorithm to converge to a solution.

显然,系统是欠定义的:您可以指定两个变量的任意值,例如 x[1]x[2] 并找到 x[0] 满足你唯一的非平凡方程.您可以通过为 x0 指定几个初始猜测来明确地看到这一点,并看到不同的输出,所有这些都满足 f(x)=0 达到一定的容差.

Clearly, the system is underdefined: you can specify arbitrary values of two variables, say, x[1] and x[2] and find x[0] to satisfy the only non-trivial equation you have. You can see this explicitly by specifying a couple of initial guesses for x0 and see different outputs, all of which satisfy f(x)=0 up to a certain tolerance.

这篇关于Python中的多元根查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆