Search code examples
rnls

nls converging but giving error


I am facing a strange issue. Is probably stupid but I don't see it and would appreciate help. Consider the following code

x<-seq(100, 1000, 100)
b<-0.3
y<-x^-b

Now let's suppose I want to fit a model and I use, for illustration purposes the following code

df <- data.frame(x = x, y = y)
nlf <- nls(y~p1*x^-p2  , data = df, start=list(p1=1,p2=1), trace = TRUE)

I get a quick convergence to the right results (as you can check). But I also get an error

5.392604e-33 :  1.0 0.3
5.392604e-33 :  1.0 0.3
5.392604e-33 :  1.0 0.3
Error in nls(y ~ p1 * x^-p2, data = df, start = list(p1 = 1, p2 = 1),  : 
  Iterationenzahl überschritt Maximum 50

Can anyone explain it? Thanks in advance.


Solution

  • From the documentation (?nls) you will see the warning: 'Do not use nls on artificial "zero-residual" data.' So the error is a product of your example which is basically perfectly fitted to your data. The explanation for why this happens can be see in the documentation. Try adding a bit of noise as below:

    x<-seq(100, 1000, 100)
    b<-0.3
    y<-x^-b + rnorm(100, 0, 0.1)  # Remember to add noise
    df <- data.frame(x = x, y = y)
    nlf <- nls(y~p1*x^-p2  , data = df, start=list(p1=1,p2=1), trace = TRUE)
    #3.591758 :  1 1
    #3.581732 :  0.6274025 0.8963628
    #3.565431 :  0.3056595 0.7399811
    #3.488972 :  0.1682877 0.5522106
    #3.263759 :  0.1895249 0.4433675
    #2.941386 :  0.2844498 0.4125101
    #2.452259 :  0.4660136 0.4015228
    #1.793046 :  0.7829449 0.3985467
    #1.172338 :  1.2573922 0.3981166
    #0.9667725 :  1.7315307 0.3981305
    #0.9667725 :  1.7315408 0.3981278