How to integrate the product of two functions

大兔子大兔子 提交于 2019-12-24 20:54:43

问题


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:

  1. First off, we choose a fixed seed for reproducibility.

    # Density funciton phi
    set.seed(2017);
    phi <- approxfun(density(rnorm(35, 15, 7)))
    
  2. 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, approxfun returns NA if x falls outside the interval [min(x), max(x)]; since phi is based on the density of a normal distribution, we can replace NAs with 0.

  3. Let's plot the integrand

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

  1. We use integrate to 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!