【问题标题】:Python: Gauss-Newton Method only correct for 1st iterationPython:高斯牛顿法仅适用于第一次迭代
【发布时间】:2023-03-06 23:42:01
【问题描述】:

我正在尝试使用 Gauss-Newton 方法在 Python 中找到 n 个圆的近交点。这里的目标是当给定点 (x1, y1), (x2, y2), ..., (xn, yn) 和半径 R1, R2, ..., Rn,高斯-牛顿法用于找到与 n 个圆的平方距离之和最小的点。

这是一种迭代方法,因此我们从初始向量 v0 = [0, 0] 开始。第一次迭代是完全正确的,但随后的迭代是不正确的。我在代码中找不到错误:

solutions = []
rmse = []

vk = [[0], [0]] # initial is set here
x = [0, 1, 0]
y = [1, 1, -1]
radii = [1, 1, 1]

iterations = 3

base_str_x = "(x _xi) / sqrt((x xi)^2 + (y yi)^2)"
base_str_y = "(y _yi) / sqrt((x xi)^2 + (y yi)^2)"
base_str_rk = "sqrt((x xi)^2 + (y yi)^2) Ri K"


it = 0
while it < iterations:
    i = 0
    A = []
    while i < len(x):
        A.append(["", ""])
        A0_str = base_str_x.replace(" xi", "%+f" % (x[i]))
        A0_str = A0_str.replace(" yi", "%+f" % (y[i]))
        A0_str = A0_str.replace("_xi", "%+f" % (x[i] * -1))
        A[i][0] = float(f(vk[0][0], A0_str, vk[1][0]))
        A1_str = base_str_y.replace(" xi", "%+f" % (x[i]))
        A1_str = A1_str.replace(" yi", "%+f" % (y[i]))
        A1_str = A1_str.replace("_yi", "%+f" % (y[i] * -1))
        A[i][1] = float(f(vk[0][0], A1_str, vk[1][0]))
        i += 1

    i = 0
    rk = []
    while i < len(x):
        rk.append([""])
        r0_str = base_str_rk.replace(" xi", "%+f" % (x[i]))
        r0_str = r0_str.replace(" yi", "%+f" % (y[i]))
        r0_str = r0_str.replace("Ri", "%+f" % (radii[i] * -1))
        rk[i][0] = float(f(vk[0][0], r0_str, vk[1][0]))
        i += 1

    lhs = np.matmul(map(list, zip(*A)), A)
    rhs = -np.matmul(map(list, zip(*A)), rk)
    vk = np.matmul(np.linalg.inv(lhs), rhs)
    solutions.append(vk)

这段代码计算A = Dr(x, y),定义为:

然后它求解方程:

vk

函数f 是一个“通用函数”,用于计算A 的每个元素。任何帮助找出为什么第一次之后的后续迭代不正确的原因将不胜感激。

【问题讨论】:

    标签: python numpy scipy numerical-methods


    【解决方案1】:

    发生这种情况的原因有两个:

    1. 括号内的符号是错误的。为了解决这个问题,在每个术语中将x[1] 乘以-1。例如A0_str = A0_str.replace(" yi", "%+f" % (y[i] * -1))
    2. 错误传播。与在后续迭代中转换为 float 相比,生成的矩阵给出的结果精确到小数位数。

    虽然第一个问题很容易解决,但第二个问题却不能。 matmul 不支持使用Decimal 并给出TypeErrorfloat64float128 数据类型不会出现增加精度。

    【讨论】:

      猜你喜欢
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多