样条的衍生物:`scipy splev`

时间:2017-02-17 22:23:46

标签: python numpy scipy curve-fitting

我试图使用pact-node中的splev在几个点找到样条曲线的导数。例如:

scipy

我想在给定点绘制切线:

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

# function to normalize each row
def normalized(a, axis=-1, order=2):
    l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
    l2[l2==0] = 1
    return a / np.expand_dims(l2, axis)

# points and spline
pts = np.array([[0,0],[1,1],[2,np.sqrt(2)],[4,2],[9,3]])
tck, u = splprep(pts.T, u=None, k=3, s=0.0, per=0)

# compute new points and derivatives
u_new = np.linspace(u.min(), u.max(), 5*u.shape[0])
x_new, y_new = splev(u_new, tck, der=0)
xp_num, yp_num = splev(pts, tck, der=1) # numerical derivatices
xp_the, yp_the= pts[1:,0], 0.5/np.sqrt(pts[1:,0]) # analytical derivatives
R = normalized(yp_num/xp_num)
X,Y = pts[1:,0], pts[1:,1]
U,V = X + R[1:,0], Y+R[1:,1]

enter image description here

我认为这些切线是错误的。我的理解是plt.plot(x_new,y_new,'-b') plt.plot(pts[:,0],pts[:,1],'--ro') plt.quiver(X,Y,U,V, angles='xy', scale_units='xy') xp_num是样条曲线相对于yp_numx的数字导数。所以要找到y,我应该简单地划分它们。这是对的吗?

最后,我想找到像this

这样的曲线的切线

2 个答案:

答案 0 :(得分:1)

你的问题(明显错误的衍生物)与数字导数无关,因为你至少在你发布的代码中没有使用它们。什么是明显错误的,除非你的from tkinter import * root = Tk() frame = Frame(root) message = Message(frame, text="hello world", width=200) message.config(fg="red", borderwidth=100, highlightcolor="green") frame.pack() message.pack() root.minsize(300, 200) root.mainloop() 函数做了真正神奇的事情是你的normalized除以yp_the,因为前者确实是增量,后者不是它应该是常数来获得

xp_the

而不是

dy
--
dx

您可能来自参数曲线的公式

 dy
----
x dx

使用了. dy -- dy dt -- = ---- dx dx -- dt ,然后忽略了t=x是不变的。发生在我们中间最好的事情。

答案 1 :(得分:1)

您没有包含R = normalized(yp_the/xp_the)来源

我是用linalg.norm

做的

然后我更改了delta_Y作为归一化导数

并放弃了箭袋

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

# points and spline
pts = np.array([[0,0],[1,1],[2,np.sqrt(2)],[4,2],[9,3]])
tck, u = splprep(pts.T, u=None, k=3, s=0.0, per=0)

# compute new points and derivatives
u_new = np.linspace(u.min(), u.max(), 5*u.shape[0])
x_new, y_new = splev(u_new, tck, der=0)
xp_num, yp_num = splev(pts, tck, der=1) # numerical derivatices
xp_the, yp_the= pts[1:,0], 0.5/np.sqrt(pts[1:,0]) # analytical derivatives
#R = normalized(yp_the/xp_the)
N = np.linalg.norm(np.array([xp_the, yp_the]), axis=0)

X,Y = pts[1:,0], pts[1:,1]
#U,V = X + R[1:,0], Y+R[1:,1]
U,V = X + xp_the/N, Y + X*yp_the/N # delta Y = dy/dx * x

plt.axes().set_aspect('equal', 'datalim')

plt.plot(x_new,y_new,'-b')
plt.plot(pts[:,0],pts[:,1],'--ro')
#plt.quiver(X,Y,U,V, scale=10, pivot='mid')# angles='xy', scale_units=’xy’, scale=1

plt.plot((X, U), (Y, V), '-k', lw=3)

enter image description here