如何整合两个函数的乘积

How to integrate the product of two functions

假设我正在寻求集成以下从 0 到 10 的函数:

我如何在 R 中完成此操作?

函数

# 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. 首先,我们选择一个固定的种子以保证可重复性。

    # Density funciton phi
    set.seed(2017);
    phi <- approxfun(density(rnorm(35, 15, 7)))
    
  2. 我们定义被积函数。

    integrand <- function(x) {
        f1 <- -500 * x^2 + 100000;
        f2 <- phi(x);
        f2[is.na(f2)] <- 0;
        return(f1 * f2)
    }
    

    默认情况下,approxfun returns NA 如果 x 落在区间 [min(x), max(x)] 之外;由于 phi 是基于正态分布的密度,我们可以将 NAs 替换为 0.

  3. 让我们绘制 integrand

    library(ggplot2);
    ggplot(data.frame(x = 0), aes(x)) + stat_function(fun = integrand) + xlim(-50, 50);
    

  1. 我们用integrate来计算积分;在这里,我假设您对区间 [-Inf, +Inf].

    感兴趣
    integrate(integrand, lower = -Inf, upper = Inf)
    #-39323.06 with absolute error < 4.6