使用“积分”计算两条线之间的面积时出错

问题描述 投票:0回答:2

我正在尝试使用 R 的

integrate
函数计算两个图之间的面积。我有两条预测曲线,可以将它们放置在同一个图上,并在两条曲线之间的区域中添加阴影,以进行可视化:

x1 = seq(1,200,1)
y1 = # 200 numbers from 0.02 - 1.000
y2 = # 200 numbers from 0.00 - 0.95

plot(x1,y1,type="l",bty="L",xlab="Forecast Days",ylab="Curve Actuals")
points(x1,y2,type="l",col="red")

polygon(c(x1,rev(x1)),c(y2,rev(y1)),col="skyblue")

按照此处的示例https://stat.ethz.ch/pipermail/r-help/2010-September/251756.html我尝试对我的数据执行相同的代码来计算两条曲线之间的距离。如示例中所述 “两条曲线之间的面积等于这两条曲线之间的差值的积分(分别是其绝对值)”

f1 = approxfun(x1, y1-y2)     # piecewise linear function
f2 = function(x) abs(f1(x))   # take the positive value

integrate(f2, 1, 200)

但是我收到以下错误:

Error in integrate(f2, 1, 200) : maximum number of subdivisions reached

感谢对此问题的任何澄清。谢谢!

r area curve numerical-integration integral
2个回答
1
投票

按照 @Roland 之前的评论中的建议,增加细分数量可以正确执行。它确实会产生绝对误差,但非常微小。

f1 = approxfun(x1, y1-y2)     # piecewise linear function
f2 = function(x) abs(f1(x))   # take the positive value

area1 = integrate(f2, 1, 200, subdivisions = 300)
> area1
9.327692 with absolute error < 8.1e-05

0
投票

approxfun()
返回一个函数吗?您需要将
f1
f2
的差异保存为函数,而不是设置点差异。例如

f1 <- function(x) { 2 * x - 1}
f2 <- function(x) { x^2 - 3 * x}
abs_dif <- function(x) { abs( f1(x) - f2(x) ) } 
integrate(abs_dif, -1, 1)

尝试将

f1
f2
表示为函数,然后尝试后两行代码。

© www.soinside.com 2019 - 2024. All rights reserved.