# Tag Info

I think that you can also solve the problem analytically. We can write the problem as $$\min_{a, b} f$$ with $$f = \sum_{i = 1}^N \int\limits_{E_i}^{E_{i + 1}}(n_i - a - bE)^2 dE \, .$$ And the minimum should happen when $\nabla f = 0$ or (I would double check) \begin{align} &\sum_{i = 1}^N \int\limits_{E_i}^{E_{i + 1}}(n_i - a - bE) dE = 0\, ,\\ &\...
Edited to correct assumption on step width If your fitting function is simply a linear relation like $a + bE$ then it's very similar to a simple linear regression (least squares) with weights. For each element (of width $w$ and centred at 0), it is simple to show that the terms in $E$ vanish so: $$\int_{-w/2}^{w/2} \left[n(E) - a - bE\right]^2 dE = w\left(n(... 2 You could use the floor function$$n(E) = \lfloor a + b E\rfloor\, . Following is an example with $a=5$ and $b=3$. import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def fun(x, a, b): return a + b*x xdata = np.linspace(-5, 5, 2001, endpoint=False) ydata = np.floor(5 + 3*xdata) popt, pcov = curve_fit(fun, ...