Generally, the data obtained from the sensor is discrete data.
In the case of discrete data, the simplest approximation is
This calculation is easy with the slice function.
import numpy as np
def diff(x, h):
res = x[2:] - x[:-2]
return res/(2*h)
In the following formula, the error is a little smaller and the error is $ \ omicron (h ^ 4) $.
def diff4(x, h):
"""
1st derivative{-f(x+2h)+8f(x+h)-8f(x-h)+f(x-2h)}/12h
x is time series data,h is the time between data(second)
"""
res = -x[4:] + 8*x[3:-1] - 8*x[1:-3] + x[:-4]
return res/(12*h)
Check each error
This time, a 1 Hz cos wave was created and differentiated.
#10second 1 Hz cos wave
time = np.linspace(0, 10, num=10000, endpoint=False)
wave = np.cos(2*np.pi*time)
#Method with many errors
vel2 = diff(wave, time[1] - time[0])
#How to reduce the error
vel4 = diff4(wave, time[1] - time[0])
#Compare with theoretical value 2π
print(vel2.max()-2*np.pi)
print(vel4.max()-2*np.pi)
Output result -4.134161924973512e-05 -3.241460433400789e-10
You can see that the latter formula has less error.
In the case of double differentiation
def diffdiff4(x, h):
"""
Derivative twice,x is time series data,h is the time between data(second)
{-f(x+2h)+16f(x+h)-30f(x)+16f(x-h)-f(x-2h)}/12h^2
"""
res = -x[4:] +16*x[3:-1] -30*x[2:-2] +16*x[1:-3] -x[:-4]
return res/(12*h*h)
Recommended Posts