# [R] making uniroot a bit more robust?

Martin Maechler maechler at stat.math.ethz.ch
Fri Nov 17 23:30:07 CET 2006

``` cleaning up my overflowing R mail box...

>>>>> "Tamas" == Tamas K Papp <tpapp at princeton.edu>
>>>>>     on Fri, 27 Oct 2006 16:11:46 -0400 writes:

Tamas> Hi, I wonder if it would make sense to make uniroot
Tamas> detect zeros at the endpoints, eg

Tamas> if f(lower)==0, return lower as the root, else if
Tamas> f(upper)==0, return upper as the root, else stop if
Tamas> f(upper)*f(lower) > 0 (currently it stops if >=),
Tamas> else proceed to the algorithm proper.

Tamas> Currently I am using a wrapper function to implement
Tamas> this, and I found it useful.  But I didn't want to
Tamas> send a (wishlist) bug report before asking on the
Tamas> list...

good practice. Sorry you didn't get an answer earlier.
"The" list should probably have been R-devel, not R-help...

The following is an example

> uniroot(function(x) x^2-1, interval=0:1)
Error in uniroot(function(x) x^2 - 1, interval = 0:1) :
f() values at end points not of opposite sign

Note that the error message is well appropriate;
However I agree that uniroot() should ideally behave a bit more
smartly.

If you provide a patch, please make sure to use something like

if ((fl <- f(lower, ...)) == 0)
return(list(root=lower, f.root=0, iter=0L, estim.prec = 0)
if ((fu <- f(upper, ...)) == 0)
return(list(root=upper, f.root=0, iter=0L, estim.prec = 0)
if (fl * fu > 0)
stop("f() values at end points are of the same sign")

or maybe there's a more elegant way.

Martin Maechler, ETH Zurich

```