A stencil can use one-sided formulas at the array edges and a centered formula in the interior.

Program

Play the program to choose an edge or interior position and compare the selected formula.

edge_stencil.f90
program edge_stencil_demo
    implicit none
    real :: values(4)
    integer :: position
    real :: slope

    values = [0.0, 10.0, 25.0, 45.0]
    position = 
    if (position == 1) then
        slope = values(2) - values(1)
    else if (position == 4) then
        slope = values(4) - values(3)
    else
        slope = (values(position + 1) - values(position - 1)) / 2.0
    end if
    print '(I0, 1X, F0.1)', position, slope
end program edge_stencil_demo
program edge_stencil_demo
    implicit none
    real :: values(4)
    integer :: position
    real :: slope

    values = [0.0, 10.0, 25.0, 45.0]
    position = 
    if (position == 1) then
        slope = values(2) - values(1)
    else if (position == 4) then
        slope = values(4) - values(3)
    else
        slope = (values(position + 1) - values(position - 1)) / 2.0
    end if
    print '(I0, 1X, F0.1)', position, slope
end program edge_stencil_demo
program edge_stencil_demo
    implicit none
    real :: values(4)
    integer :: position
    real :: slope

    values = [0.0, 10.0, 25.0, 45.0]
    position = 
    if (position == 1) then
        slope = values(2) - values(1)
    else if (position == 4) then
        slope = values(4) - values(3)
    else
        slope = (values(position + 1) - values(position - 1)) / 2.0
    end if
    print '(I0, 1X, F0.1)', position, slope
end program edge_stencil_demo
edge case The first and last positions cannot read on both sides.
one-sided stencil Edge positions subtract the nearest neighbor on the inside.
centered stencil Interior positions can use values on both sides.