【问题标题】:How to integrate the product of two functions如何整合两个功能的乘积
【发布时间】:2018-06-13 02:25:36
【问题描述】:

假设我正在寻求从 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

【问题讨论】:

  • "整合以下功能"整合哪个功能?哪个变量?在哪个时间间隔内?
  • 另外:approxfun 是什么?那是自定义功能吗?来自外部 R 库的函数?
  • @MauritsEvers 来自stats
  • @akrun 该死的,我的错。从来没有遇到过approxfun。很高兴知道。谢谢。

标签: r calculus


【解决方案1】:

以下内容如何:

  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)
    }
    

    默认情况下,如果x 超出区间[min(x), max(x)],则approxfun 返回NA;由于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
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 2015-09-23
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多