Source code for edlgt.tools.derivatives

"""Finite-difference derivative helpers on uniformly spaced 1D grids.

This module provides simple central-difference routines for first and second
derivatives. Both functions return the derivative evaluated on the interior
points only (the first and last grid points are dropped).
"""

import numpy as np

__all__ = ["first_derivative", "second_derivative"]


[docs] def first_derivative(grid_values, function_values, dx): """Compute the first derivative using a central-difference stencil. Parameters ---------- grid_values : numpy.ndarray One-dimensional grid values. Only interior points are returned. function_values : numpy.ndarray Function values sampled on ``grid_values``. dx : float Uniform grid spacing. Returns ------- tuple ``(x_interior, df_dx)`` as two NumPy arrays, both of length ``len(grid_values) - 2``. Notes ----- This routine assumes a uniformly spaced grid and uses the standard second-order central-difference approximation on interior points. """ derivative_values = ( function_values[2:] - function_values[:-2] ) / (2 * dx) interior_grid = np.array(grid_values[1:-1], copy=True) return interior_grid, derivative_values
[docs] def second_derivative(grid_values, function_values, dx): """Compute the second derivative using a central-difference stencil. Parameters ---------- grid_values : numpy.ndarray One-dimensional grid values. Only interior points are returned. function_values : numpy.ndarray Function values sampled on ``grid_values``. dx : float Uniform grid spacing. Returns ------- tuple ``(x_interior, d2f_dx2)`` as two NumPy arrays, both of length ``len(grid_values) - 2``. Notes ----- This routine assumes a uniformly spaced grid and uses the standard second-order central-difference approximation on interior points. """ derivative_values = ( function_values[2:] - 2 * function_values[1:-1] + function_values[:-2] ) / (dx**2) interior_grid = np.array(grid_values[1:-1], copy=True) return interior_grid, derivative_values