使用“积分"计算两条线之间的面积时出错 [英] Error calculating the area between two lines using "integrate"

查看:37
本文介绍了使用“积分"计算两条线之间的面积时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 R 的 integrate 函数计算两个图之间的面积.我有两条预测曲线,我可以将它们放在同一个图上,并在两条曲线之间的区域进行阴影处理,以进行可视化:

I'm attempting to calculate the area between two plots using R's integrate function. I have two forecast curves that I'm able to place on the same plot and also shade in the area between the two curves, for visualisation:

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 我试图为我的数据执行相同的代码来计算两条曲线之间的均值.如示例中所述两条曲线之间的面积等于这两条曲线之间的差值的积分(及其绝对值)":

Following the example here https://stat.ethz.ch/pipermail/r-help/2010-September/251756.html I've attempted to execute the same code for my data to calculate the are between the two curves. As stated in the example "the area between two curves is the same as the integral of the difference between these two curves (resp. its absolute values)":

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

感谢您对此的任何澄清.谢谢!

Appreciate any clarity that can be shed on this. Thanks!

推荐答案

增加细分的数量,正如@Roland 之前的评论中所建议的那样,可以正确执行.它确实会产生绝对错误,但非常微小.

Increasing the number of subdivisions, as suggested in an earlier comment by @Roland, executes correctly. It does produce an absolute error, but very minute.

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

这篇关于使用“积分"计算两条线之间的面积时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆