Clicky
Showing changes from revision #0 to #1:
(追記) Added (追記ここまで) | (削除) Removed (削除ここまで) | (削除) Chan (削除ここまで)(追記) ged (追記ここまで)
The function below is expressed using whole-array operations, so the interior derivatives should be automatically vectorized by the compiler, yielding fast code. A different method necessarily has to be used to calculate the derivatives at the edges. This implementation uses a central difference approximation (second order) in the interior, and forward/backward difference approximations (first order) at the edges.
pure function differentiate(x, y) result(r)
!! This function calculates the numerical derivative of an array y with respect to x, using a central difference approximation
!! at the interior points and forward/backward difference approximations at the exterior points. Note that since all the three
!! approaches yield two-point approximations of the derivative, the mesh spacing of x does not necessarily have to be uniform.
real(wp), intent(in) :: x(:) !! Variable x
real(wp), intent(in) :: y(size(x)) !! Function y(x)
real(wp) :: r(size(x)) !! Derivative dy/dx
! Differentiate using finite differences
associate(n => size(x))
r( 1 ) = (y( 1+1 ) - y( 1 ))/(x( 1+1 ) - x( 1 ))
r(1+1:n-1) = (y(1+2:n) - y(1:n-2))/(x(1+2:n) - x(1:n-2))
r( n ) = (y( n ) - y( n-1 ))/(x( n ) - x( n-1 ))
end associate
end function