首页 > 解决方案 > 计算极坐标中样条曲线的梯度

问题描述

我想计算样条曲线的梯度并在极坐标图中将其可视化。

我使用tck, u = splprep()笛卡尔坐标获得样条曲线并splev(u, tck, der=1)分别计算其在 x 和 y 方向上的偏导数。然后,我计算应该可视化渐变的箭头的端点并将它们转换为极坐标。

乍一看,该图看起来不错,但如果我将估计的梯度方向与解析解进行比较,即使我增加点数,也会存在显着差异。

MWE

from matplotlib import pyplot as plt
import numpy as np
from scipy.interpolate import splprep, splev

if __name__ == '__main__':
    N = 11  # number of samples
    # x = np.arange(0, N)  # [Update] This did not decrease the step size for increasing N
    x = np.linspace(0, 10, N)
    y = np.sin(x)

    tck, u = splprep([x, y], s=0)  # spline

    theta, r = np.arctan2(y, x), np.hypot(x, y)  # convert to polar

    gradient = splev(u, tck, der=1) # compute first derivative

    # normalize
    gradient = gradient / np.hypot(gradient[0], gradient[1])

    # compare numerical and analytical solution
    # direction = np.arctan2(gradient[1], gradient[0])  # [Update] this was wrong
    slope = gradient[1] / gradient[0]
    print(np.cos(x) - slope)  # cos(x) should be the analytical solution

    endpoints_x = x + gradient[0]
    endpoints_y = y + gradient[1]

    # convert cartesian endpoints to polar
    endpoints_theta, endpoints_r = np.arctan2(endpoints_y, endpoints_x),\
                                   np.hypot(endpoints_x, endpoints_y)


    fig, ax = plt.subplots(1, 1, subplot_kw=dict(polar=True))

    plt.scatter(theta, r, marker='o')

    plt.plot(np.stack((theta, endpoints_theta)), np.stack((r, endpoints_r)), 'r')

    plt.show()

截屏

极坐标中样条曲线的梯度

更新

我发现了两个错误。首先,步长并没有随着我使用x的增加而减少。其次,我希望数值解是,但它只是笛卡尔坐标中的斜率。Nnp.arange(0, N)arctan2(gradient[1], gradient[0])gradient[1] / gradient[0]

现在一切都按预期工作。

标签: pythonmatplotlibsplinepolar-coordinates

解决方案


推荐阅读