python - 计算极坐标中样条曲线的梯度
问题描述
我想计算样条曲线的梯度并在极坐标图中将其可视化。
我使用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
的增加而减少。其次,我希望数值解是,但它只是笛卡尔坐标中的斜率。N
np.arange(0, N)
arctan2(gradient[1], gradient[0])
gradient[1] / gradient[0]
现在一切都按预期工作。
解决方案
推荐阅读
- javascript - HTML5 背景视频无法播放
- c# - MVC Net Core 从多个页面收集数据
- elasticsearch - Elasticsearch 中的复制
- ios - 允许用户使用来自不同视图控制器中的标签的文本创建新的 tableViewCells?
- json - 从 Invoke-RestMethod 访问 JSON 格式的数据
- mysql - MySQL 两种更新方式
- java - Java 指令重新排序示例不起作用
- javascript - 获取下载文件的cordova(离子)上的文件大小
- c++ - 在基于英语的系统上将 UTF-8 路径转换为宽字符会引发异常
- ios - 异步调用 AudioKit AKMidiSampler.loadMelodicSoundFont