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)
  2.329599 seconds (3.35 M allocations: 224.017 MiB, 1.14% gc time, 99.98% compilation time)
2-element Vector{Float64}: 1.0048062429652467 1.970910458750898

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

# 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))
  4.434137 seconds (4.53 M allocations: 314.589 MiB, 1.61% gc time, 99.95% compilation time)
Fitted parameters: [3.0, 2.0, 0.7]
Prediction at x=5: 9.170338627200096

This notebook was generated using Literate.jl.