
When I now use lmfit, I get the following output: ] So I first use np.log on the original data and then do the fit. I fit them - as suggested by - by transforming the power law in a linear function: y = N * x ** a Since you do not provide any data, I created some which are shown here: Please find this solution below after the EDIT which can hopefully serve as a minimal example on how to use scipy's curve_fit with parameter bounds.Īs suggested by Weckesser, you could use lmfit to get this task done, which allows you to assign bounds to your parameters and avoids this 'ugly' if-clause. Starting with version 0.17, scipy also allows to assign bounds to your parameters directly (see documentation). In the original post, I showed a solution that uses lmfit which allows to assign bounds to your parameters. Do I need to write my own least-squares algorithm or is there something I'm doing wrong here? 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. 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. 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. Using _fit yields an awful fit (green line), returning values of 1.2e+04 and 1.9e0-7 for N and a, respectively, with absolutely no intersection with the data. Where the else condition is just to force a to be positive.

So, I'm trying to fit a set of data with a power law of the following kind: def f( x,N,a): # Power law fit if a > 0:
