【问题标题】:How can I plot this 'integral' code in R?如何在 R 中绘制这个“积分”代码?
【发布时间】:2021-04-12 02:35:51
【问题描述】:
f1 <- function(x){integrate(f = function(t){
  sqrt(t^3-1)
}, lower = 1, upper = x)}

x 的域是14f1 总是发出以“集成”为特征的值。我不知道如何在 R 中绘制这个积分函数。 感谢任何可以帮助我的人。

【问题讨论】:

    标签: r plot integral


    【解决方案1】:

    您可能需要计算函数 f1 的值,然后按如下方式使用 apply 函数:

    f1 <- function(x) {
      integrate( function(t) sqrt(t^3-1), lower = 1, upper = x)
    }
    u <- seq(1, 4, by = 0.1) # Defining a vector of values from 1 to 4 in steps of .1
    f1u <- sapply(u, function(x) f1(x)$value) #computing the values of f1 over u
    plot(u,f1u, type = "l", xlab = "x", ylab = "f1(x)") # your plot
    

    【讨论】:

    • 谢谢保罗!你给了我很多帮助。
    • 很高兴为您提供帮助,请考虑支持并接受答案。谢谢
    【解决方案2】:

    您可以像这样将upper 参数矢量化为integrate

    vintegrate <- Vectorize(integrate, "upper")
    
    f1 <- function(x) {
      unlist(vintegrate(function(t) sqrt(t^3-1), lower = 1, upper = x)[1,])
    }
    

    然后您可以使用基础R 中的curve 函数进行绘图:

    curve(f1(x), from = 1, to = 4)
    

    或者使用ggplot2:

    library(ggplot2)
    
    ggplot(data.frame(x  = 0)) + 
      geom_function(fun = f1) +
      xlim(1, 4)
    


    如果没有向量化,upper 参数需要一个长度为 1 的向量,否则会出错:

    integrate(function(t) sqrt(t^3-1), lower = 1, upper = 1:4)
    Error in integrate(function(t) sqrt(t^3 - 1), lower = 1, upper = 1:4) : 
      length(upper) == 1 is not TRUE
    

    矢量化后:

    vintegrate(function(t) sqrt(t^3-1), lower = 1, upper = 1:4)
                 [,1]       [,2]         [,3]         [,4]        
    value        0          1.515927     5.356315     11.84309    
    abs.error    0          0.0001312847 0.0003641383 0.0006563824
    subdivisions 1          5            5            5           
    message      "OK"       "OK"         "OK"         "OK"        
    call         Expression Expression   Expression   Expression  
    

    我们使用unlist[1,] 来获得value

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 2020-11-17
      相关资源
      最近更新 更多