问题
Suppose I am seeking to integrate the following function from 0 to 10:
How would I accomplish this in R?
Functions
# Functional form
fn <- function(t) -100*(t)^2 + 20000
# First derivative w.r.t. t
fn_dt <- function(t) -200*t
# Density funciton phi
phi <- approxfun(density(rnorm(35, 15, 7)))
# Delta t
delta <- 5
回答1:
How about the following:
First off, we choose a fixed seed for reproducibility.
# Density funciton phi set.seed(2017); phi <- approxfun(density(rnorm(35, 15, 7)))We define the integrand.
integrand <- function(x) { f1 <- -500 * x^2 + 100000; f2 <- phi(x); f2[is.na(f2)] <- 0; return(f1 * f2) }By default,
approxfunreturnsNAifxfalls outside the interval[min(x), max(x)]; sincephiis based on the density of a normal distribution, we can replaceNAs with0.Let's plot the
integrandlibrary(ggplot2); ggplot(data.frame(x = 0), aes(x)) + stat_function(fun = integrand) + xlim(-50, 50);
We use
integrateto calculate the integral; here I assume you are interested in the interval[-Inf, +Inf].integrate(integrand, lower = -Inf, upper = Inf) #-39323.06 with absolute error < 4.6
来源:https://stackoverflow.com/questions/50828266/how-to-integrate-the-product-of-two-functions