I can't get this boxcar fit working...I get " OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning)", and the output coefficients are not improved beyond the starting guess.
import numpy as np
from scipy.optimize import curve_fit
def box(x, *p):
height, center, width = p
return height*(center-width/2 < x)*(x < center+width/2)
x = np.linspace(-5,5)
y = (-2.5<x)*(x<2.5) + np.random.random(len(x))*.1
coeff, var_matrix = curve_fit(box, x, y, p0=[1,0,2])
The output coefficients are [ 1.04499699, 0., 2.], not that the third one has not even been changed.
I suspect that this functional form is not amenable to the levenberg-marquardt algorithm used by curve_fit, which is kind of annoying because I like this function. In mathematica it would be trivial to specify a monte carlo optimization, instead.

