【问题标题】:having trouble with finding multiple roots of a system of equations with scipy fsolve无法使用 scipy fsolve 找到方程组的多个根
【发布时间】:2022-10-18 19:50:31
【问题描述】:

具有如下两个耦合方程的系统:

two_exponential = lambda x, kernel, c: np.array([x[0] - np.exp(kernel[0] * x[0] + kernel[2] * x[1] + c), x[1] - np.exp(kernel[1] * x[1] + kernel[3] * x[0] + c)])

我想找到两条线与scipy.fsolve 的交点。 我这样做的方法是为b11,b22, b12, b21 的不同配置找到这个系统的根源。

b = np.array([b11, b22, b12, b21])
x_min_plot = -10
x_max_plot = 35
x_1 = np.linspace(x_min_plot, x_max_plot, 100)
x_2 = np.linspace(x_min_plot, x_max_plot, 100)
x_1, x_2 = np.meshgrid(x_1, x_2)
z_1 = -x_1 + np.exp(b[0] * x_1 + b[2] * x_2 + c)
z_2 = -x_2 + np.exp(b[1] * x_2 + b[3] * x_1 + c)
x_sols = []
x_min = 0
x_max = 35

for x in np.arange(x_min, x_max, 5):
    for y in np.arange(x_min, x_max, 5):
        initial = np.array([x, y])
        x_sol = fsolve(two_exponential, initial, args=(b, c), full_output=1)
        if x_sol[2] == 1: # if the solution converged
            x_sols.append(np.round(x_sol[0], 2))
# [x for i, x in enumerate(x_sols) if not np.isclose(x, x_sols[i-1], atol = 1e-1).all()]
x_sols = np.unique(x_sols, axis=0)


print(f'z*: {np.round(x_sols, 2)}')
if x_sol[2] != 1:
    print('no solution')

我还将解决方案四舍五入以忽略重复的根,因为我只想找到唯一的根。 该代码在某些情况下似乎可以正常工作:

但不适用于其他一些条件:

你知道这样的问题会从哪里出现吗?

【问题讨论】:

  • 降低误差容限。当近似值足够好时,该方法将停止,如果图​​形在感兴趣区域中较浅,则可能会出错。
  • 可以消除未知数 X1 或 X2 之一以获得单变量方程。
  • 请注意,在您的两个示例中,解决方案接近渐近线。所以它们的交点可以做出很好的初始近似。

标签: python scipy numerical-methods


【解决方案1】:

感谢所有的cmets。我用一个简单的技巧克服了这个问题。由于 fsolve 方法正在寻找系统的根,因此将解输入回函数应该导致零。我添加了另一个 if 语句并检查解决方案是否实际上为零并且只接受这些解决方案。

if x_sol[2] == 1: # if the solution converged
   if np.isclose(two_exponential(x_sol[0], b, c), 0, atol = 1e-3).all():

这解决了问题。我需要提到问题仍然存在,我不知道为什么 fsolve 会这样做。我在 fsolve 中更改了“xtol

但这并没有多大帮助。无论如何,现在通过检查根是否真的是根来解决问题!

【讨论】:

    猜你喜欢
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多