Many, many thanks to the numerous individuals who took the time to answer
my question regarding computing the area between two curves.
I also wrote my own function to do this last night. It is shown below.
Please pardon any long winded geometry. I was working from memory since I
had no geometry book around.
triangle.fun <- function(s1,s2,s3)
{
# Returns the area of a triangle given length of sides
s1<-abs(s1);s2<-abs(s2);s3<-abs(s3)
s <- (s1+s2+s3)/2
a <- sqrt(s*(s-s1)*(s-s2)*(s-s3))
return(a)
}
area.quad.fun <- function(x,y1,y2)
{
# Intermediate function that takes x, y1, and y2 all length 2.
# Then returns the area between the two line segments.
# Unlike some functions, this allows the line segments to intersect.
diff <- y2-y1
if(prod(diff)>= 0)
{
a <- y2[1]-y1[1]
b <- sqrt((x[1]-x[2])^2+(y1[1]-y1[2])^2)
c <- y2[2] - y1[2]
d <- sqrt((x[1]-x[2])^2+(y2[2]-y2[1])^2)
l <- sqrt((x[1]-x[2])^2+(y2[1]-y1[2])^2)
Area <- triangle.fun(a,b,l)+triangle.fun(c,d,l)
}
else
{
a <- y2[1]-y1[1]
c <- y2[2]-y1[2]
m1<- (y1[2]-y1[1])/(x[2]-x[1])
m2<- (y2[2]-y2[1])/(x[2]-x[1])
b1<-y1[2]-m1*x[2]
b2<-y2[2]-m2*x[2]
x3<-(b2-b1)/(m1-m2)
y3<-m1*x3+b1
b1<-sqrt((x3-x[1])^2+(y3-y1[1])^2)
b2<-sqrt((x3-x[1])^2+(y3-y2[1])^2)
d1<-sqrt((x3-x[2])^2+(y3-y1[2])^2)
d2<-sqrt((x3-x[2])^2+(y3-y2[2])^2)
Area <- triangle.fun(a,b1,b2)+triangle.fun(c,d1,d2)
}
return(Area)
}
areaBetweenCurves.fun <- function(x,y1,y2)
{
# length(x)=length(y1)=length(y2)
# Computes areas between y1 and y2 curves.
# And plots segments
area<-0
for(i in 1:(length(x)-1))
{
area <- area+area.quad.fun(x[i:(i+1)],y1[i:(i+1)],y2[i:(i+1)])
}
plot(x,y1,type="l",ylim=c(min(c(y1,y2)),max(c(y1,y2))))
lines(x,y2)
return(area)
}
> x <- c(0,1,2)
> y1<- c(0,0,1)
> y2<- c(1,1,0)
> areaBetweenCurves.fun(x,y1,y2)
[1] 1.5
|