如何解决计算极坐标中样条曲线的梯度
我想计算样条曲线的梯度,并在极坐标图中将其可视化。
我用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()
屏幕截图
更新
我发现了两个错误。首先,当我使用x
时,N
中的步长并没有通过增加np.arange(0,N)
而减小。其次,我期望数值解为arctan2(gradient[1],gradient[0])
,但它只是笛卡尔坐标中的斜率gradient[1] / gradient[0]
。
现在一切正常。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。