scipy curve_fit strange result
<p>I am trying to fit a distribution with scipy's curve_fit. I tried to fit a one component exponential function which resulted in an almost straight line (see figure). I also tried a two component exponential fit which seemed to work nicely. Two components just means that a part of the equation repeats with different input parameters. Anyway, here is the one component fit function:</p>

<pre><code>def Exponential(Z,w0,z0,Z0):
    z = Z - Z0
    termB = (newsigma**2 + z*z0) / (numpy.sqrt(2.0)*newsigma*z0)
    termA = (newsigma**2 - z*z0) / (numpy.sqrt(2.0)*newsigma*z0)
    return w0/2.0 * numpy.exp(-(z**2 / (2.0*newsigma**2))) * (numpy.exp(termA**2)*erfc(termA) + numpy.exp(termB**2)*erfc(termB))
</code></pre>

<p>and the fitting is done with</p>

<pre><code>fitexp = curve_fit(Exponential,newx,y2)
</code></pre>

<p>Then I tried something, just to try it out. I took two parameters of the two component fit, but did not use them in the calculation.</p>

<pre><code>def ExponentialNew(Z,w0,z0,w1,z1,Z0):
    z = Z - Z0
    termB = (newsigma**2 + z*z0) / (numpy.sqrt(2.0)*newsigma*z0)
    termA = (newsigma**2 - z*z0) / (numpy.sqrt(2.0)*newsigma*z0)
    return w0/2.0 * numpy.exp(-(z**2 / (2.0*newsigma**2))) * (numpy.exp(termA**2)*erfc(termA) + numpy.exp(termB**2)*erfc(termB))
</code></pre>

<p>And suddenly this works.</p>

<p><a href="https://i.stack.imgur.com/jhq0S.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/jhq0S.jpg" alt="enter image description here"></a></p>

<p>Now, my quation is. WHY? As you can see, there is absolutely no difference in the calculation of the fit. It just gets two extra variables that are not used. Should this not get the same result?</p>

<p>In my experience <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow"><code>curve_fit</code></a> can sometimes act up and stick with the initial values for the parameters. I would suspect that in your case adding a few fake parameters changed the heuristics of how the relevant parameters are being initialized (although this contradicts the documentation's statement that with no initial values given, they all default to 1).</p>

<p>It helps a lot in obtaining reliable fits if you specify reasonable bounds and initial values for your fitting parameters (I mean the <code>p0</code> and <code>bounds</code> keywords). The fact that the default starting values should all be <code>1</code> suggests that for most use cases, the default won't cut it.</p>

python scipy