title: SciPy Curve Fit Fails Power Law
body: <p>So, I'm trying to fit a set of data with a power law of the following kind:</p>
  
  <pre><code>def f(x,N,a): # Power law fit
      if a &gt;0:
          return N*x**(-a)
      else:
          return 10.**300
  
  par,cov = scipy.optimize.curve_fit(f,data,time,array([10**(-7),1.2]))
  </code></pre>
  
  <p>where the else condition is just to force a to be positive. Using scipy.optimize.curve_fit yields <a href="http://i.imgur.com/i1difuV.png" rel="noreferrer">an awful fit (green line)</a>, returning values of 1.2e+04 and 1.9e0-7 for N and a, respectively, with absolutely no intersection with the data. From fits I've put in manually, the values should land around 1e-07 and 1.2 for N and a, respectively, though putting those into curve_fit as initial parameters doesn't change the result. Removing the condition for a to be positive results in a worse fit, as it chooses a negative, which leads to a fit with the wrong sign slope.</p>
  
  <p>I can't figure out how to get a believable, let alone reliable, fit out of this routine, but I can't find any other good Python curve fitting routines. Do I need to write my own least-squares algorithm or is there something I'm doing wrong here?</p>