LsqFit¶
LsqFit.jl package is a small library that provides basic least-squares fitting in pure Julia.
using LsqFit
@. model(x, p) = p[1] * exp(-x * p[2])
# Generate data
xdata = range(0, stop=10, length=20)
ydata = model(xdata, [1.0 2.0]) + 0.01 * randn(length(xdata))
# Initial guess
p0 = [0.5, 0.5]
# Fit the model
@time fit = curve_fit(model, xdata, ydata, p0; autodiff=:forwarddiff)
# The result should be close to `[1.0 2.0]`
coef(fit) 1.880028 seconds (6.93 M allocations: 333.491 MiB, 99.97% compilation time: 2% of which was recompilation)
2-element Vector{Float64}:
1.0008561034738157
2.005284014226261CurveFit¶
Linear, special function, and nonlinear curve fitting in Julia.
The algorithms used in CurveFit.jl are better suited for ill-conditioned nonlinear systems as stated in JuliaCon 2025
See a list of algorithms in the documentation.
using CurveFit
# Define a nonlinear function: y = a[1] + a[2] * x^a[3]
fn(a, x) = @. a[1] + a[2] * x^a[3]
# True parameters
true_params = [3.0, 2.0, 0.7]
# Generate sample data
x = collect(1.0:0.5:10.0)
y = fn(true_params, x)
# Create problem with initial guess for parameters
u0 = [0.5, 0.5, 0.5]
prob = NonlinearCurveFitProblem(fn, u0, x, y)
@time sol = solve(prob)
println("Fitted parameters: ", sol.u)
println("Prediction at x=5: ", sol(5.0)) 3.005894 seconds (7.67 M allocations: 383.638 MiB, 1.53% gc time, 99.93% compilation time)
Fitted parameters: [2.9999999999999996, 2.0000000000000004, 0.6999999999999998]
Prediction at x=5: 9.170338627200096
This notebook was generated using Literate.jl.