简体   繁体   中英

Tangent to curve interpolated from discrete data

I was wondering if there's a way to find tangents to curve from discrete data. For example:

x = np.linespace(-100,100,100001)
y = sin(x)

so here x values are integers, but what if we want to find tangent at something like x = 67.875 ?

I've been trying to figure out if numpy.interp would work, but so far no luck. I also found a couple of similar examples, such as this one , but haven't been able to apply the techniques to my case :( I'm new to Python and don't entirely know how everything works yet, so any help would be appreciated...

this is what I get: 在此处输入图片说明

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-100,100,10000)
y = np.sin(x)
tck, u = interpolate.splprep([y])

ti = np.linspace(-100,100,10000)
dydx = interpolate.splev(ti,tck,der=1)

plt.plot(x,y)
plt.plot(ti,dydx[0])
plt.show()

There is a comment in this answer , which tells you that there is a difference between splrep and splprep . For the 1D case you have here, splrep is completely sufficient.

You may also want to limit your curve a but to be able to see the oscilations.

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-15,15,1000)
y = np.sin(x)
tck = interpolate.splrep(x,y)

dydx = interpolate.splev(x,tck,der=1)

plt.plot(x,y)
plt.plot(x,dydx, label="derivative")

plt.legend()
plt.show()

在此处输入图片说明

While this is how the code above would be made runnable, it does not provide a tangent. For the tangent you only need the derivative at a single point. However you need to have the equation of a tangent somewhere and actually use it; so this is more a math question.

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-15,15,1000)
y = np.sin(x)
tck = interpolate.splrep(x,y)

x0 = 7.3
y0 = interpolate.splev(x0,tck)
dydx = interpolate.splev(x0,tck,der=1)

tngnt = lambda x: dydx*x + (y0-dydx*x0)

plt.plot(x,y)
plt.plot(x0,y0, "or")
plt.plot(x,tngnt(x), label="tangent")

plt.legend()
plt.show()

在此处输入图片说明

It should be noted that you do not need to use splines at all if the points you have are dense enough. In that case obtaining the derivative is just taking the differences between the nearest points.

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-15,15,1000)
y = np.sin(x)

x0 = 7.3
i0 = np.argmin(np.abs(x-x0))
x1 = x[i0:i0+2]
y1 = y[i0:i0+2]
dydx, = np.diff(y1)/np.diff(x1)

tngnt = lambda x: dydx*x + (y1[0]-dydx*x1[0])

plt.plot(x,y)
plt.plot(x1[0],y1[0], "or")
plt.plot(x,tngnt(x), label="tangent")

plt.legend()
plt.show()

The result will be visually identical to the one above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM