Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

SciPy · Function

curve_fit

Fits a callable model to measured data using nonlinear least squares. It returns optimized parameters and an approximate covariance matrix, with options for uncertainty weighting, bounds, optimization methods, and diagnostics.

How it works

curve_fit estimates parameters for a callable model by minimizing residuals between model predictions and observed data. It returns the best-fit parameter vector and an approximate covariance matrix, while supporting measurement uncertainties, parameter bounds, optimization methods, Jacobians, missing-value policies, and optional diagnostic output.

Syntax

scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=None, bounds=(-inf, inf), method=None, jac=None, *, full_output=False, nan_policy=None, **kwargs)

Parameters

NameTypeDescription
fcallableThe model function, f(x, …). Its first argument is the independent variable; remaining arguments are fitted parameters.
xdataarray_likeIndependent-variable measurements.
ydataarray_likeDependent observations, nominally f(xdata, ...).
p0array_like, optionalInitial parameter estimate; defaults to ones when parameters can be inferred.
sigmaarray_like, optionalMeasurement uncertainty as a scalar, sequence, or covariance matrix.
absolute_sigmabool, optionalWhether sigma should be interpreted in absolute terms when estimating covariance.
check_finitebool, optionalWhether to check input finiteness; defaults depend on nan_policy.
bounds2-tuple of array_like or Bounds, optionalLower and upper parameter bounds.
method{‘lm’, ‘trf’, ‘dogbox’}, optionalOptimization method: lm, trf, or dogbox.
jaccallable or string, optionalJacobian of the model with respect to parameters, or a finite-difference scheme name.
full_outputbool, optionalReturn additional optimization information.
nan_policy{None, ‘raise’, ‘omit’}, optionalHow to handle NaN values: raise or omit.

Returns

Returns popt, a one-dimensional array of optimized parameter values, and pcov, a two-dimensional approximate covariance matrix. With full_output=True, also returns infodict, errmsg, and ier.

Key points

  • Use curve_fit when a parametric callable should be calibrated against observed data through nonlinear least squares.
  • The fitting model treats observations as model predictions plus an error term.
  • The returned popt contains the parameter values that minimize the residual sum of squares.
  • The returned pcov approximates parameter covariance and can be used to assess fit uncertainty.
  • Select the optimization algorithm with method, including lm, trf, or dogbox.

Common mistakes

  • Define the model with the independent variable first, followed by one positional argument per fitted parameter.
  • Adding bounds changes the default optimization method; choose explicitly when method behavior matters.
  • Use floating-point inputs and model outputs to avoid incorrect results caused by unsuitable numeric types.

Example: Fit a straight line

import numpy as np
from scipy.optimize import curve_fit

x = np.arange(6.0)
y = 2.0 * x + 1.0

def model(x, slope, intercept):
    return slope * x + intercept

popt, pcov = curve_fit(model, x, y)
print(popt)
print(np.sqrt(np.diag(pcov)))

Fits a straight-line model and prints the optimized parameters and their approximate standard errors.

When to use it

Parametric calibration

Estimate coefficients in a nonlinear physical, statistical, or engineering model from paired measurements.

Weighted fitting

Incorporate known observation uncertainty into the objective and covariance estimate.

Constrained optimization

Restrict fitted parameters to physically meaningful intervals.

Interview questions

QWhat problem does curve_fit solve?

curve_fit performs nonlinear least-squares fitting. It assumes the observations follow ydata = f(xdata, *params) + eps and returns parameters that minimize the squared residuals.

Follow-up: How are bounds handled? With bounds, the default method is trf; without bounds, it is lm.

QWhat interface must the model function implement?

f must be callable with the independent variable as its first argument and fitted parameters as separate remaining arguments. xdata contains measured independent-variable values, and ydata contains the corresponding dependent values.

Follow-up: What must change for a model with three unknowns? Add three parameter arguments after x in f and provide data compatible with the model output.

QWhat does curve_fit return?

The function returns popt, the parameter values minimizing the residual sum of squares, and pcov, an approximate covariance matrix for popt. Standard deviations can be derived from the diagonal of pcov.

Follow-up: What does sigma affect? It weights residuals, and absolute_sigma controls whether its absolute scale is used when estimating covariance.

  • scipy.optimize.least_squares
  • scipy.optimize.leastsq
  • scipy.optimize.OptimizeWarning

Source: curve_fit. Checked 2026-10-15.