Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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)
  3.927048 seconds (13.70 M allocations: 661.498 MiB, 4.63% gc time, 99.98% compilation time: <1% of which was recompilation)
2-element Vector{Float64}: 1.0000325544247997 1.9859325510920702

CurveFit

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
using NonlinearSolve

# 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))
  5.518451 seconds (12.37 M allocations: 777.566 MiB, 8.28% gc time, 99.96% compilation time)
Fitted parameters: [3.0, 1.9999999999999998, 0.7000000000000001]
Prediction at x=5: 9.170338627200096

This notebook was generated using Literate.jl.