问题描述
我有两个简单的方程:
k = 2.013*h^0.4917 and h = 3.57*k^0.4917
这些方程可以解析求解,其中 k = 5.77 和 h = 8.47。我尝试使用 fsolve 在 Python 中解决它,我遵循了以下方法: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html#scipy.optimize.fsolve
下面是我的代码:
from scipy.optimize import fsolve
def equations(x):
return[x[0] - 2.013*x[1]**0.4917,x[1] - 3.57*x[0]**0.4917]
root = fsolve(equations,[1,1])
结果是
<ipython-input-133-11ce0ecaa7e4>:2: RuntimeWarning: invalid value encountered in double_scalars
return[x[0] - 2.013*x[1]**0.4917,x[1] - 3.57*x[0]**0.4917]
RuntimeWarning: The iteration is not making good progress,as measured by the
improvement from the last ten iterations.
warnings.warn(msg,RuntimeWarning)
print(root)
array([1.,1.])
我不确定我在这里做错了什么,导致我没有得到正确的结果。你想指出我在这个问题上的错误吗?谢谢。
解决方法
-
fsolve
不知道您的变量是非负的。求解器进入负区域(因为从 (1,1) 梯度告诉走向负区域),在那里获得 NaN,然后卡住。你应该以某种方式告诉你在哪里寻找解决方案。fsolve
不直接支持边界。least_squares
可以做到这一点。 -
有几种解决方案。 (0,0) 也是合适的。您可能不得不以某种方式摆脱它,因为这似乎不是您想要从求解器那里得到的。
您可以尝试类似的方法。
from scipy.optimize import least_squares
def equations(x):
return[x[0] - 2.013*x[1]**0.4917,x[1] - 3.57*x[0]**0.4917]
root = least_squares(equations,[2,2],bounds=([1,1],[10,10]))
print(root)
x: array([5.74279193,8.43196966])