R/Trapezoid.R

#' A class to handle numerical integration with the trapezoid method
#' @export
#' @seealso \link{Integrator}
Trapezoid = setClass("Trapezoid", contains = "Integrator")

#' Performs integration according to the Trapezoid rule.
#'
#' @param object The object containing the values to integrate.
#'
#' @return The numerical integral of the provided values.
#' @export
setMethod("integrateIt",
		  signature = (type = "Trapezoid"),
		  function(type, ...) {
		  	start.index  = which(type@x == type@start)
		  	end.index    = which(type@x == type@end)
		  	target.range = start.index : end.index

		  	x.range = type@x[target.range]
		  	y.range = type@y[target.range]

	  		step = 2:length(type@x)
	  		x.values = x.range[step] - x.range[step - 1]
	  		y.values = y.range[step] + y.range[step - 1]
	  		return(sum(x.values * y.values / 2))
		  })

#' Validates the correctness of the arguments passed to X.
#'
#' @param object The object to validate.
#' @export
validate.trapezoid = function(object) {
	if (object@start >= object@end) {
		stop("End must be greater than Start.")
	}
	if (length(object@x) != length(object@y)) {
		stop("X and Y must be the same length.")
	}
}


#' Initializes Simpson objects, and validates them.
#'
#' @param .Object Simpson. The object to initialize.
#' @export
setMethod("initialize", signature(.Object = "Trapezoid"),
		  function(.Object, x, y, start, end) {
		  	.Object@x = x
		  	.Object@y = y
		  	.Object@start = start
		  	.Object@end = end
		  	validate.trapezoid(.Object)
		  	.Object@result = integrateIt(.Object)
		  	return(.Object)
		  }
)
alexjweil/integrateIt documentation built on May 10, 2019, 8:54 a.m.