计算极坐标中样条曲线的梯度

问题描述

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

我用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,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()

屏幕截图

Gradient of a spline in polar coordinates

更新

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

现在一切正常。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...