【发布时间】:2021-04-12 02:35:51
【问题描述】:
f1 <- function(x){integrate(f = function(t){
sqrt(t^3-1)
}, lower = 1, upper = x)}
x 的域是1 到4。 f1 总是发出以“集成”为特征的值。我不知道如何在 R 中绘制这个积分函数。
感谢任何可以帮助我的人。
【问题讨论】:
f1 <- function(x){integrate(f = function(t){
sqrt(t^3-1)
}, lower = 1, upper = x)}
x 的域是1 到4。 f1 总是发出以“集成”为特征的值。我不知道如何在 R 中绘制这个积分函数。
感谢任何可以帮助我的人。
【问题讨论】:
您可能需要计算函数 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
【讨论】:
您可以像这样将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。
【讨论】: