Python, scipy.optimize.curve_fit do not fit to a linear equation where the slope is known
<p>I think I have a relatively simple problem but I have been trying now for a few hours without luck. I am trying to fit a linear function (linearf) or power-law function (plaw) where I already known the slope of these functions (b, I have to keep it constant in this study). The results should give an intercept around 1.8, something I have not managed to get. I must do something wrong but I can not point my finger on it. Does somebody have an idea how to get around this problem?</p>

<p>Thank you in advance!</p>

<pre><code>import numpy as np
from scipy import optimize


p2 = np.array([  8.08543600e-06,   1.61708700e-06,   1.61708700e-05,
                 4.04271800e-07,   4.04271800e-06,   8.08543600e-07])

pD = np.array([ 12.86156,  16.79658,  11.52103,  21.092  ,  14.47469,  18.87318])

# Power-law function
def plaw(a,x):

    b=-0.1677 # known slope
    y = a*(x**b)

    return y

# linear function
def linearf(a,x):

    b=-0.1677 # known slope
    y = b*x + a

    return y

## First way, via power-law function ##

popt, pcov = optimize.curve_fit(plaw,p2,pD,p0=1.8)

# array([  7.12248200e-37]) wrong

popt, pcov = optimize.curve_fit(plaw,p2,pD)
# &gt;&gt;&gt; return 0.9, it is wrong too (the results should be around 1.8)


## Second way, via log10 and linear function ##

x = np.log10(p2)
y = np.log10(pD)

popt, pcov = optimize.curve_fit(linearf,x,y,p0=0.3)

K = 10**popt[0]
## &gt;&gt;&gt;&gt; return 3.4712954470408948e-41, it is wrong
</code></pre>

<p>I just discover an error in the functions:</p>

<p>It should be : </p>

<pre><code>def plaw(x,a):

    b=-0.1677 # known slope
    y = a*(x**b)

    return y
</code></pre>

<p>and not</p>

<pre><code>def plaw(a,x):

b=-0.1677 # known slope
y = a*(x**b)

return y
</code></pre>

<p>Stupid mistake.</p>

python python-2.7