# [R] how to see what's wrong with a self written function?

jim holtman jholtman at gmail.com
Wed Dec 22 01:53:50 CET 2010

```Here is what I get when I have:

options(error=utils::recover)

I always run with the option so that on an error, I get dumped in the
browser to see what is happening.  It appears that 'i == 3' when the
error occurs and you can also see the values of 'x':

> regulafalsi=function(f,x0,x1){
+        x=c()
+        x=x1
+        i=1
+        while ( f(x[i])!=0 ) {
+                i=i+1
+                if (i==2) {
+                        x=x-f(x)*(x-x0)/(f(x)-f(x0))
+                } else {
+
x[i]=x[i-1]-f(x[i-1])*(x[i-1]-x[i-2])/(f(x[i-1])-f(x[i-2]))
+                }
+        }
+        x[i]
+ }
> regulafalsi(function(x) x^(1/2)+3*log(x)-5,10,1)
 2.978429
> regulafalsi(function(x) x^(1/2)+3*log(x)-5,1,100)
Error in while (f(x[i]) != 0) { : missing value where TRUE/FALSE needed
In log(x) : NaNs produced

Enter a frame number, or 0 to exit

1: regulafalsi(function(x) x^(1/2) + 3 * log(x) - 5, 1, 100)

Selection: 1
Called from: top level
Browse> i
 3
Browse> x
 100.00000  18.35661 -42.22301
Browse>

On Tue, Dec 21, 2010 at 2:39 PM, casperyc <casperyc at hotmail.co.uk> wrote:
>
> Hi all,
>
> I am writing a simple function to implement regularfalsi (secant) method.
>
> ###################################################
> regulafalsi=function(f,x0,x1){
>        x=c()
>        x=x1
>        i=1
>        while ( f(x[i])!=0 ) {
>                i=i+1
>                if (i==2) {
>                        x=x-f(x)*(x-x0)/(f(x)-f(x0))
>                } else {
>                        x[i]=x[i-1]-f(x[i-1])*(x[i-1]-x[i-2])/(f(x[i-1])-f(x[i-2]))
>                }
>        }
>        x[i]
> }
> ###################################################
>
> These work fine,
> regulafalsi(function(x) x^(1/2)+3*log(x)-5,1,10)
> regulafalsi(function(x) x^(1/2)+3*log(x)-5,10,1)
>
> For all x>0, the function is strictly increasing.
>
> Then
>
> regulafalsi(function(x) x^(1/2)+3*log(x)-5,1,100)
>
> Error in while (f(x[i]) != 0) { : missing value where TRUE/FALSE needed
> In log(x) : NaNs produced
>
> I dont know what happened there, is there a way to find the value for
> f(x[i])
> that R can't determine TRUE/FALSE?
>
> Thanks!
>
> casper
> --
> View this message in context: http://r.789695.n4.nabble.com/how-to-see-what-s-wrong-with-a-self-written-function-tp3159528p3159528.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

--
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?

```