[R] Derivative

TGS cran.questions at gmail.com
Thu Aug 12 08:43:55 CEST 2010


This following works for me but I still favor the quick and dirty method suggested originally by David.

options(scipen = 10)
x <- seq(0,2, by = .01)
f <- expression(5*cos(2*x)-2*x*sin(2*x))
D(f, 'x')
f.prime <- function(x){
	-(5 * (sin(2 * x) * 2) + (2 * sin(2 * x) + 2 * x * (cos(2 * x) * 2)))
}
curve(expr = f.prime, from = 1, to = 2, n = 101)
uniroot(f = f.prime, interval = c(1,2), tol = .00001)

On Aug 11, 2010, at 10:56 PM, David Winsemius wrote:


On Aug 12, 2010, at 12:49 AM, Dennis Murphy wrote:

> Hi:
> 
> Try the following:
> 
> f <- function(x) 5*cos(2*x)-2*x*sin(2*x)
> curve(f, -5, 5)
> abline(0, 0, lty = 'dotted')
> 
> This shows rather clearly that your function has multiple roots, which isn't
> surprising given that it's a linear combination of sines and cosines. To
> find a specific root numerically, use function uniroot on f, as follows:
> 
>> uniroot(f, c(0, 2))

Except he was asking for the root of the derivative. If the classroom assignment allows use of R's limited symbolic differentiation you could try:

> df.dx <- D(expression(5*cos(2*x)-2*x*sin(2*x)), "x")
> df.dx
-(5 * (sin(2 * x) * 2) + (2 * sin(2 * x) + 2 * x * (cos(2 * x) *
   2)))
(Which as one of the examples in the deriv help page notes is not the most simple form.)

I was assuming that the OP wanted a solution to:

d( abs(f(x)) )/dt  = 0 in the domain [1,2]

So:
f.df.dx <- function (x) {
    eval(parse(text=D(expression(5*cos(2*x)-2*x*sin(2*x)), "x") ) )
                       }
#  no abs() but we should be satisfied with either a minimum or a maximum
uniroot(f.df.dx, c(1,2) )

$root
[1] 1.958218267

$f.root
[1] 1.138013788e-05

$iter
[1] 4

$estim.prec
[1] 6.103515625e-05

It doesn't agree with my earlier method and I think this one has a greater probablity of being correct. I don't think I needed to take second differences.

-- 
David.

> $root
> [1] 0.6569286
> 
> $f.root
> [1] -0.0001196119
> 
> $iter
> [1] 6
> 
> $estim.prec
> [1] 6.103516e-05
> 
> This catches the root that lies between x = 0 and x = 2. If you want to find
> a set of roots, you can try a loop. Fortunately, since the function is even,
> you really only need to find the roots on one side of zero, since the ones
> on the other side are the same with opposite sign.
> 
> lo <- seq(0, 4.5, by = 1.5)
> hi <-  seq(1.5, 6, by = 1.5)
> roots <- numeric(length(lo))
> 
> for(i in seq_along(lo)) roots[i] <- uniroot(f, c(lo[i], hi[i]))$root
> roots
> 
> See ?uniroot for other options and tolerance settings.
> 
> HTH,
> Dennis
> 
> On Wed, Aug 11, 2010 at 6:21 PM, TGS <cran.questions at gmail.com> wrote:
> 
>> How would I numerically find the x value where the derivative of the
>> function below is zero?
>> 
>> x <- seq(1,2, by = .01)
>> y <- 5*cos(2*x)-2*x*sin(2*x)
>> plot(x,abs(y), type = "l", ylab = "|y|")
> 
-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list