R/utils_math.R

Defines functions safe_log_base trapz_num

Documented in safe_log_base trapz_num

#' Numerical trapezoidal integration
#'
#' @param x Numeric grid values.
#' @param y Numeric function values on the grid.
#'
#' @return A numeric scalar.
#' @keywords internal
trapz_num <- function(x, y) {
  x <- as.numeric(x)
  y <- as.numeric(y)

  if (length(x) != length(y)) {
    stop("x and y must have the same length.")
  }
  if (length(x) < 2) {
    stop("x and y must have length >= 2.")
  }

  i <- 2:length(x)
  sum((x[i] - x[i - 1]) * (y[i] + y[i - 1]) / 2)
}


#' Log with package-supported base
#'
#' @param x Numeric vector.
#' @param base Logarithm base. Defaults to 2. Must be either 2 or exp(1).
#'
#' @return Numeric vector.
#' @keywords internal
safe_log_base <- function(x, base = 2) {
  check_base(base)
  log(x) / log(base)
}

Try the jsdtools package in your browser

Any scripts or data that you put into this service are public.

jsdtools documentation built on March 31, 2026, 1:06 a.m.