0

Using R I'd like to automatically find the tangent to a curve of diminishing returns for an optimal foraging graphical exercise. The curve looks like this:

ins <- 40
t <- 30
avg <- 30
curve(ins/2^(x/10+1-1),
    0,2*t,xlim=c(-2*t,2*t),ylim=c(ins,0),
    xlab="time",ylab="food",type="l",lty=1,col=4,lwd=3,axes=FALSE)
axis(1,pos=ins); axis(2,pos=0)

The tangent starts at points (-40,40) and ideally I would find the point on the curve the tangent would touch.

By trial & error it should look like:

segments(-ins,ins,38,0,col=4,lwd=3,lty=2)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • maybe take a look at this [SOF/29642867](https://stackoverflow.com/questions/29642867/drawing-a-tangent-to-the-plot-and-finding-the-x-intercept-using-r?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – Chris May 20 '18 at 21:05

1 Answers1

1

Setup:

ins <- 40
t <- 30
avg <- 30

deriv(...,function.arg=TRUE) returns a function that gives the value of the function as its main result, and the gradient as an attribute.

FUN <- deriv(~ins/2^(x/10+1-1),"x",function.arg=TRUE)
curve(FUN(x),
      0,2*t,xlim=c(-2*t,2*t),
      ylim=c(ins,0),
      xlab="time",ylab="food",type="l",
      lty=1,col=4,lwd=3,axes=FALSE)
axis(1,pos=ins); axis(2,pos=0)

We need to solve the equation ((40+x)*D(x)+40=f(x)) (where D(x) is the gradient and f(x) is the function value):

Translating that equation to a function that will return 0 when the equation is true:

rfun <- function(x) {
  f <- FUN(x)
  (40+x)*attr(f,"gradient")+40-f
} 
u1 <- uniroot(rfun,c(-40,60))

Derivative at the intersection point:

d1 <- attr(FUN(u1$root),"gradient")

Draw the segment:

segments(x0=-40,y0=40,x1=40,y1=40+(40+40)*d1,
         col=4,lwd=3,lty=2)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Great Ben, works like a charm. Many thanks for your help. Have still to understand your answer step by step, but will eventually get there. That's what happens when you usually do not need calculus in your profession. – Thomas Dellinger May 22 '18 at 09:43