library(ggplot2); library(magrittr)
Here we instantiate:
\[ \frac{1}{12 dx} (-25x_{i} + 48x_{i-1} - 36x_{i-2} + 16x_{i-3} - 3x_{i-4}) \]
FPoint = function(xx, dx){
## xx is the vector of data, dx is the timestep between the data. This is necessary for proper scaling.
n = length(xx)
dydx = vector()
dydx[1:4] = NA
for(i in 5:n){
dydx[i] = (-1/dx) * (1/12) * (-25*xx[i] + 48*xx[i-1] - 36*xx[i-2] + 16*xx[i-3] - 3*xx[i-4])
}
return(dydx)
}
Let’s take it for a spin, shall we?
x = seq(0, 2*pi, length = 100)
cosx = cos(x)
dx = FPoint(cosx, dx = x[2] - x[1])
cd = data.frame(x, cosx, dx)
cd %>% ggplot(aes(x = x, y = cosx, color = 'blue')) + geom_point() + geom_point(aes(x = x, y = dx, color = 'red')) + theme(legend.position="none")
## Warning: Removed 4 rows containing missing values (geom_point).
One more?
x = seq(-10, 10, length = 100)
lnx = x^2
dx = FPoint(lnx, (x[3]-x[2]))
ld = data.frame(x, lnx, dx)
ld %>% ggplot(aes(x = x, y = lnx, color = 'blue')) + geom_point() + geom_point(aes(x = x, y = dx, color = 'red'))+ theme(legend.position="none")
## Warning: Removed 4 rows containing missing values (geom_point).