logo

How to Use Finite Difference in Julia 📂Julia

How to Use Finite Difference in Julia

Overview

To use Finite Differences in Julia, more specifically to calculate the coefficients of finite differences, it is advisable to use FiniteDifferences.jl1. In cases where there is susceptibility to noise, it’s possible to use Total Variation Regularized Numerical Differentiation, known as TVDiff, implemented in NoiseRobustDifferentiation.jl.

Code

FiniteDifferenceMethod()

julia> f′ = FiniteDifferenceMethod([-2, 0, 5], 1)
FiniteDifferenceMethod:
  order of method:       3
  order of derivative:   1
  grid:                  [-2, 0, 5]
  coefficients:          [-0.35714285714285715, 0.3, 0.05714285714285714]


julia> typeof(f′)
FiniteDifferences.UnadaptedFiniteDifferenceMethod{3, 1}

The example above calculates the first-order derivative using the middle point of the function, the second point from the left, and the fifth point from the right, providing the weights of these three points. The basic thing that FiniteDifferenceMethod() provides is these coefficients.

julia> propertynames(f′)
(:grid, :coefs, :coefs_neighbourhood, :condition, :factor, :max_range, :∇f_magnitude_mult, :f_error_mult)

julia> f′.grid
3-element StaticArraysCore.SVector{3, Int64} with indices SOneTo(3):
 -2
  0
  5

julia> f′.coefs
3-element StaticArraysCore.SVector{3, Float64} with indices SOneTo(3):
 -0.35714285714285715
  0.3
  0.05714285714285714

The properties to be used in the structure primarily include .grid and .coefs.

julia> f′(sin, π/2)
-1.2376571459669071e-11

julia> f′(cos, π/2)
-1.0000000000076525

When the function itself is given instead of data, it’s perfectly fine to write it directly as a function form as seen above.

_fdm()

central_fdm(2, 1)
central_fdm(3, 2)
backward_fdm(4, 1)
forward_fdm(5, 1)

If you need a well-known FDM without customizations, it’s more convenient to use the function already provided as seen above. The first argument depends on how many points will be used according to the type of the function, and the second argument $n$ determines that it will calculate the $n$ derivative. Obviously, when the first argument of central_fdm() is given as an odd number, the coefficient of the central point is definitely 0.

Full Code

using FiniteDifferences

f′ = FiniteDifferenceMethod([-2, 0, 5], 1)
typeof(f′)
propertynames(f′)
f′.grid
f′.coefs

f′(sin, π/2)
f′(cos, π/2)

central_fdm(2, 1)
central_fdm(3, 2)
backward_fdm(4, 1)
forward_fdm(5, 1)

Environment

  • OS: Windows
  • julia: v1.8.5