# Custom nonlinear curve fitting package?

**URL:** https://discourse.julialang.org/t/custom-nonlinear-curve-fitting-package/103468
**Category:** General Usage
**Tags:** curve-fitting
**Created:** [September 2, 2023, 7:15pm UTC](https://discourse.julialang.org/t/custom-nonlinear-curve-fitting-package/103468 "2023-09-02T19:15:15Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![PeX](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pex/32/49986_2.png) [@PeX](https://discourse.julialang.org/u/PeX)
#### Post date: [September 2, 2023, 7:15pm UTC](https://discourse.julialang.org/t/custom-nonlinear-curve-fitting-package/103468/1 "2023-09-02T19:15:15Z")

</div>

Hi all!  
I have a dataset that I want to fit a function to in the form of:  
y = a x^4 + b x^3 + c x^2 + dx + e + f sin(gx + h)  
I was trying to use LsqFit.jl , but the results are not great (unless I guess the parameters myself).  
Is there another package that might do a better job?

My LsqFit.jl attempt looks like this (maybe I can tweak something for better results?):

```julia
function fit_strain_poly(time, strain, A, f, ϕ, a, b, c, d, e)
P = [A, f, ϕ, a, b, c, d, e]
t0 = time 
@. model(t, p) = p[1]*sin(2*pi*p[2]*t - p[3]) + p[4]*t^4 + p[5]*t^3 + p[6]*t^2 + p[7]*t + p[8]
fit = curve_fit(model,t0,strain,P)
A_f = fit.param[1]
f_f = fit.param[2]
ϕ_f = fit.param[3]
a_f = fit.param[4]
b_f = fit.param[5]
c_f = fit.param[6]
d_f = fit.param[7]
e_f = fit.param[8]
strain_f = model(t0, fit.param)
return strain_f, A_f, f_f, ϕ_f, a_f, b_f, c_f, d_f, e_f	
end

fit_s1_poly, A1_poly, f1_poly, ϕ1_poly, a1_poly, b1_poly, c1_poly, d1_poly, e1_poly = fit_strain_poly(time_1, ε_1,4e-2, 3.36e-3, 9e-1, 0.1, 0.001, 0.1, 0.2, 0.1);

```

---

<div class="post-metadata">

### Author: ![mbaz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mbaz/32/17295_2.png) [@mbaz](https://discourse.julialang.org/u/mbaz)
#### Post date: [September 2, 2023, 10:31pm UTC](https://discourse.julialang.org/t/custom-nonlinear-curve-fitting-package/103468/2 "2023-09-02T22:31:34Z")

</div>

Adding that specific fit is on my todo list for [SinusoidalRegressions](https://github.com/mbaz/SinusoidalRegressions.jl). The algorithm I have in mind is based on [this document](https://mbaz.github.io/SinusoidalRegressions.jl/v0.2/#citeref-2), page 54. Its main advantage is that it does not require initial estimates. I hope I have time to implement it soon, but PRs are welcome too!
