rsolvernonlinear-functions

How can I solve the optimal solution of a system of overdetermined nonlinear equations using R


library(BB)
library(nleqslv)
library(reprex)
library(ktsolve)

yfunc<-function(x){
   y<-vector()
   y[1]<-a+b*sin((238.61/365)+c)-(39393*0.00341802+149-273.15)
   y[2]<-a+b*sin((1821.2/365)+c)-(38795*0.00341802+149-273.15)
   y[3]<-a+b*sin((1946.8/365)+c)-(38875*0.00341802+149-273.15)
   y[4]<-a+b*sin((2072.4/365)+c)-(39231*0.00341802+149-273.15)
   y[5]<-a+b*sin((2111.36/365)+c)-(38505*0.00341802+149-273.15)
   y[6]<-a+b*sin((2223.12/3650)+c)-(37962*0.00341802+149-273.15)
   y
}
guess=list(a=8,b=15,c=30)
solv1<-ktsolve(yfunc,guess = guess)
#> Error in ktsolve(yfunc, guess = guess): Fewer guesses than equations.  System is underdefined.

I want to use multiple equations to find the optimal solution of a nonlinear equation. How should I configure the function? Created on 2021-09-01 by the reprex package (v2.0.1)


Solution

  • We can use nonlinear least squares to find the parameter values that minimize the sum of the squares of the differences of the two sides of the the following model. We use the plinear algorithm which only requires that we provide starting values for the parameters that enter non-linearly, in this case only c. As there are two parameters that enter linearly, the right hand side should be a two column matrix which will be matrix multiplied by the vector of those parameters: c(a, b) . No packages are used.

    x <- c(238.61, 1821.2, 1946.8, 2072.4, 2111.36, 2223.12) / 365
    y <- c(39393, 38795, 38875, 39231, 38505, 37962) * 0.00341802 + 149 - 273.15
    
    fm <- nls(y ~ cbind(a = 1, b = sin(x + c)), start = list(c = 30), alg = "plinear"); fm
    ## Nonlinear regression model
    ##   model: y ~ cbind(a = 1, b = sin(x + c))
    ##    data: parent.frame()
    ##      c .lin.a .lin.b 
    ## 30.255 12.226  4.598 
    ##  residual sum-of-squares: 10.72
    ##
    ## Number of iterations to convergence: 4 
    ## Achieved convergence tolerance: 1.47e-09