[R] fit data to y~A+B*sin(C*x)

Berend Hasselman bhh at xs4all.nl
Tue Feb 14 16:24:11 CET 2012


On 13-02-2012, at 23:54, Jonas Stein wrote:

> I want to fit discrete data that was measured on a wavegenerator.
> In this minimal example i generate some artificial data:
> 
> testsin <- 2+ 5 * sin(1:100) #generate sin data
> testsin <-  testsin+ rnorm(length(testsin), sd = 0.01) #add noise
> 
> mydata <- list(X=1:100, Y=testsin) # generate mydata object
> 
> nlmod <- nls(X ~ A+B*sin(C* Y), data=mydata, start=list(A=2, B=4, C=1), trace=TRUE)
> 
> # this nls fit fails. 

What do you mean by "fail"
> nlmod
Nonlinear regression model
  model:  X ~ A + B * sin(C * Y) 
   data:  mydata 
      A       B       C 
50.7553  0.6308  0.8007 
 residual sum-of-squares: 83308

Number of iterations to convergence: 24 
Achieved convergence tolerance: 7.186e-06 

Results don't seem to look ok.
But I think you made a small mistake in the formula.
The argument to sin in testsin is 1:100 but that's not what you are giving nls.

Try this

> nlmod <- nls(Y ~ A+B*sin(C* X), data=mydata, start=list(A=2, B=4, C=1), trace=TRUE)
50.30593 :  2 4 1 
0.01014092 :  2.0003732 5.0002681 0.9999979 
0.01014016 :  2.0003732 5.0002681 0.9999983 
> nlmod
Nonlinear regression model
  model:  Y ~ A + B * sin(C * X) 
   data:  mydata 
A B C 
2 5 1 
 residual sum-of-squares: 0.01014

Number of iterations to convergence: 2 
Achieved convergence tolerance: 1.201e-07 

Looks better?

Berend



More information about the R-help mailing list