R/numeric_tools.R

Defines functions num_diff num_int

Documented in num_diff num_int

#' Differentiate on a Grid
#'
#' @param f A sequence of values of a function
#' @param grid The corresponding x axis
#'
#' @return The derivative on the grid.
#' @export
#'
#' @examples
#' x <- seq(from = 0, to = 2 * pi, by = 0.01)
#' f <- sin(x)
#' df <- num_diff(f, x)
#'
#' plot(x, cos(x), type = "l", col = "red")
#' points(x, df, col = "blue")
#'
num_diff <- function(f, grid){
  stopifnot(length(f) == length(grid))
  n <- length(f)
  res <- numeric(n)
  delta <- diff(grid)
  res[1:(n - 1)] <- (f[2:n] - f[1:(n - 1)]) / delta
  res[n] <- res[n - 1]
  return(res)
}


#' Integrate on a Grid
#'
#' @param f A sequence of values of a function
#' @param grid The corresponding x axis
#' @param constant Optional constant to add to the derivative.
#'
#' @return The integral between the start of the grid up until the grid.
#' @export
#'
#' @examples
#' x <- seq(from = 0, to = 2 * pi, by = 0.01)
#' f <- sin(x)
#' int_f <- num_int(f, x, -1)
#'
#' plot(x, -cos(x), type = "l", col = "red")
#' points(x, int_f, col = "blue")
#'
num_int <- function(f, grid, constant = 0){
  cumsum(c(0, diff(grid) * (f[1:(length(grid) - 1)] + f[2:length(grid)])/2)) + constant
}
osorensen/mytools documentation built on May 3, 2019, 5:47 p.m.