Fitting a complicated function usually means starting with a diagnostic pass, then reserving the hardest machinery for the part that truly needs it. If the model is smooth and mildly nonlinear, bounded least squares with scaled parameters and sensible starting values will often finish the job; if it contains exponentials, poles, thresholds, or many coupled parameters, you need to reformulate, stage the fit, or switch method before trusting any result. The single most common cause of failure isn't a weak optimizer—it's a model written in a form the data can't identify, or a solver asked to explore a parameter space no optimizer can navigate.

Below is a complete workflow for turning a messy "fit this complicated function" request into a fit you can defend. It assumes real measured data and a model you can write down, with some parameters to estimate.

Fix the problem statement before you touch a solver

Curve fitting is the search for parameter values that make a chosen model match data under a stated loss. The model, the loss, the noise assumption, and the parameter constraints together define the problem. When someone says a fit is "impossible," one of those four is usually wrong.

Write down four things before fitting:

1: The model equation as an explicit function of the independent variable(s) and named parameters. 2: The noise model. Is error additive, multiplicative, Poisson-like, or something else? Which axis carries the error? This determines whether you minimize squared residuals, weighted squared residuals, or a likelihood. 3: The parameter domain. Which parameters must stay positive? Which are bounded? Are any discrete? 4: The question the fit must answer. A prediction at new inputs, a physical constant with an uncertainty, or a smooth trend line all tolerate different compromises.

A model that predicts well but produces a physically meaningless parameter is still a failed fit for a parameter-estimation question. Decide which outcome matters before choosing a method.

Diagnose why the function is "complicated"

Most hard fitting problems fall into a few recognizable families. Naming the difficulty tells you which remedy applies.

Multi-scale parameters. Decay rates spanning 1e-4 and 1e2, or lengths in nanometers and millimeters, make the residual surface a narrow ravine. Gradient-based solvers crawl; finite-difference gradients lose precision. Remedy: scale parameters and residuals.

Strong parameter correlation. Two parameters that trade off against each other create a ridge with many near-equivalent fits. Remedy: reparameterize, add data in a region that separates them, or report the ridge honestly.

Local minima. Models with oscillations, phase shifts, or multiple exponentials have many basins. Remedy: multistart, global search, or a better initial guess from a reduced problem.

Non-identifiability. Some parameter combinations may be estimable while individual parameters are not. A model like a + b·exp(-c·t) with t sampled only at large values cannot separate a and b well; only their sum is identified. Remedy: recognize the invariant combination, fix or regularize parameters, or collect data in the informative region.

Heavy tails or outliers. Least squares chases outliers. Remedy: robust loss or explicit outlier modeling.

Ill-conditioning from model form. A ratio with a near-zero denominator, or an exponent that overflows, produces numerical noise. Remedy: reformulate—fit the log, use log-sum-exp, or cap exponents.

A quick diagnostic: if the model is a sum of exponentials, the number of distinct decay rates is the hardest thing to estimate, not the amplitudes. If the model is a rational function, poles near the data region dominate. If the model involves a phase, correlation between phase and frequency is your enemy.

Prepare data and parameters

Before fitting, run a short checklist. Skip it and downstream debugging gets much harder.

Inspect residuals from a naive fit. Even a crude fit reveals outliers, saturation, or a data gap that will confuse the solver.

Estimate noise level. From repeated measurements or from residuals away from sharp features. This sets expected parameter uncertainty and the weighting.

Clean obviously bad points deliberately. Document what was removed and why. Silent filtering is a form of data fabrication.

Count data against parameters. A model with 15 parameters and 20 points fits everything and estimates nothing. Check the effective sample size relative to parameter count, especially if parameters are constrained.

Scale each parameter to order one. Let θ = θ₀ + s·u where s is a characteristic scale (a rate, a length, a magnitude you measured). Fit u, not θ. If you can't guess a scale, use the magnitude of a first-order estimate from a simplified fit.

Scale residuals. Divide residuals by the estimated noise standard deviation on each axis, so the optimizer sees comparable numbers.

This scaling step alone resolves a large fraction of "the optimizer won't converge" complaints.

Start with the simplest model that could work

Fit a reduced version first. Drop parameters you can't yet justify, fix the ones with external estimates, and see whether the reduced model explains the bulk of the variation. A successful reduced fit gives you starting values and an upper bound on the residual you should expect from the full model.

For example, if your function is a sum of two Gaussians plus a baseline, fit baseline plus one Gaussian first. The fitted width and center become excellent initial guesses for the full fit, and you learn whether a second component is actually needed.

Success check: residuals of the reduced fit should hover around the noise level except at features the reduced model cannot capture. If residuals are huge everywhere, the model form, not the parameter values, is wrong.

Choose a loss that matches the noise

The default is unweighted least squares, which is the maximum-likelihood choice for additive Gaussian noise with constant variance. Choose otherwise when the data says otherwise:

Multiplicative or proportional error: minimize squared relative residuals, or fit in log space if the model permits. Counts: a Poisson likelihood or deviance instead of plain squares. Heteroscedastic measurements: weighted least squares with weights proportional to inverse variance. Outliers or heavy tails: Huber or Tukey loss, or a mixture model with an outlier component.

In log space, remember that minimizing squared differences of logs is equivalent to a different loss on the original scale. Decide which scale carries the physically meaningful error, and be consistent when quoting uncertainties.

Fit with bounded least squares, then examine the result

For a smooth model with a modest parameter count, bounded least squares is the workhorse. The procedure:

1: Supply initial values from the reduced fit. 2: Supply bounds wide enough to contain the physically plausible range but tight enough to prevent absurd excursions (negative rates, runaway amplitudes). 3: Fit with scaled parameters. 4: Inspect the covariance matrix, the correlation matrix, and the residuals.

The correlation matrix is the single most underused output. Correlations near ±0.99 between parameters tell you the fit is resting on a ridge. You can still report a prediction, but the individual parameters are nearly arbitrary. Report the invariant combination or add constraints.

The residual pattern should be structureless. A systematic wiggle means another term is missing; an upward trend at the end of a range means your functional form is wrong at the boundary.

Success check: parameter standard errors derived from the covariance should be small compared with parameter values for well-determined parameters, and residual distribution should match the assumed noise. If the standard errors are large but predictions are tight, you're in a correlated regime—address it honestly rather than hiding it.

Escalate to global or staged methods

When bounded least squares returns wildly different answers from different starting values, the problem has multiple basins. Options, in roughly increasing effort:

Multistart local fitting. Run the local fit from dozens or hundreds of scrambled starting points and cluster the results. Cheap and often sufficient.

Global optimizers. Differential evolution, simulated annealing, or a basin-hopping strategy search more broadly. Use these to locate basins, then polish with a local fit. Global methods are slow and do not provide covariance estimates directly—the polish step is mandatory.

Staged or profile fitting. Fix subsets of parameters, fit the rest, then release the fixed set. This is especially effective for multi-exponential or peak-fitting problems where amplitudes can be solved linearly given the shapes.

Variable projection. If the model is linear in some parameters (amplitudes in a sum of exponentials, coefficients in a basis expansion), separate them: solve the linear part exactly for each candidate set of nonlinear parameters, and optimize only over the nonlinear ones. This reduces the search dimension dramatically and is a well-established method for this class of problem.

Reparameterization. Replace parameters that are entangled with combinations that are not. Examples: fit amplitude and time constant of an exponential separately versus fitting the product in a scaled form; fit a ratio and a difference instead of two correlated quantities; constrain a phase parameter via sine and cosine components.

A stop condition: if after multistart and reparameterization the fit still lands in physically implausible regions with small residuals, your model likely encodes an assumption contradicted by the data. Stop tuning and revisit the model.

Handle non-identifiable and boundary cases

Sometimes the data simply cannot determine a parameter, or the best fit sits on a bound.

At a bound: if the optimum is exactly at a physical limit, the asymptotic covariance formulas are invalid. Report the bound, the profile of the objective near the bound, and a likelihood-ratio interval instead of standard errors.

Weakly identified parameter: report the profile likelihood for that parameter—fix it at a grid of values, refit the others, and plot the resulting objective. The shape of that curve tells you what the data supports far better than a covariance matrix.

Fundamentally non-identifiable combination: fit only the identifiable combinations (for example, ratios or sums) and state clearly what cannot be separated.

Degenerate covariance: square roots of negative diagonal entries mean the linearization is meaningless. Trust the profile, not the matrix.

Estimate uncertainty honestly

Uncertainty from the covariance matrix is only as good as the linear, Gaussian approximation. For complicated models it often isn't good enough. Use, in order of preference when feasible:

1: Profile likelihood for each parameter of interest. 2: Bootstrap (residual or parametric) for empirical confidence intervals, especially with small samples. 3: Posterior sampling (for example, Markov chain Monte Carlo) if you have prior information and a probabilistic model. 4: Covariance matrix as a quick first pass, clearly labeled as approximate.

Report the method used. A parameter with a justified interval and a stated method is more useful than a precise-looking number with no provenance.

Worked failure example: sum of exponentials

Suppose you fit a two-exponential decay, A·exp(-k₁t) + B·exp(-k₂t), and every run gives k₁ and k₂ nearly equal, with huge covariance between them. The symptom is a ridge: the data barely distinguish two similar rates. Remedies, in order: fix the ratio k₂/k₁ to a physically motivated value or scan it on a grid; reparameterize into a single exponential plus a small correction; or acknowledge that the two-rate model is over-specified for this dataset and report the single rate. Each of these is a legitimate response, and choosing among them is a scientific judgment, not a numerical one.

A second common failure: fitting in linear space a function that includes an exponential of a parameter times a coordinate. If the parameter can take values that make the exponent enormous, the exponential overflows and the optimizer receives infinite or NaN residuals. Fix by bounding the parameter, working in log space where valid, or clipping the exponent and penalizing the clip in a smooth way.

Verify, then report

A fit isn't finished until you've checked it against data it didn't see, if any is available, or against residuals and predictions if not.

Residual plot: structureless, at the expected noise level. Prediction band: does the uncertainty in predictions match observed scatter of held-out points? Parameter plausibility: are values consistent with independent estimates or physical bounds? Sensitivity: if you perturb the initial guess, does the optimum stay put? Model comparison: if a simpler model fits nearly as well, prefer it unless the extra parameters are physically required.

What to report: the model equation, the fitted parameters with uncertainty method and intervals, the loss value, the number of data and parameters, the diagnostic residual summary, and the code or settings sufficient to reproduce the fit. For softw

are workflows, saving the configuration file and recording the version numbers counts as reproducibility. For parameter questions, the invariant combinations and their uncertainties matter more than a spurious complete set.

If you must force a choice, prefer the fit whose parameters you can explain and defend over the one with the smallest residuals.

Frequently Asked Questions

Can I fit a function that contains an integral or a differential equation?

Yes, but each evaluation of the model becomes a numerical computation, so the cost per residual is high. Keep the number of parameters as small as possible, supply good starting values from a simplification, and compute gradients carefully—finite differences on a numerical integral are noisy. If the integral is inside the model in a way that's differentiable, consider autodifferentiation.

What if my model is a black box I can only evaluate?

You can still fit with derivative-free methods (pattern search, Nelder–Mead, or a global optimizer followed by local polishing), but expect many more evaluations and less reliable uncertainty estimates. Budget accordingly and don't trust covariance output from finite differences on a noisy black box.

How do I know I have enough data?

At minimum, the number of data points should comfortably exceed the number of parameters, and those points should sample every region where the function changes. As a rough guide, a model with p parameters deserves at least several times p informative points, more when parameters are strongly correlated.

Is it ever correct to fix parameters?

Often, yes—when external evidence constrains them tightly, or when the data cannot identify them. A fixed parameter with a clearly cited external value is more honest than a fitted parameter whose value is arbitrary due to a ridge.