Python,scipy.optimize.curve_fit不适合已知斜率的线性方程

时间:2016-09-23 11:40:07

标签: python python-2.7

我认为我有一个相对简单的问题,但我现在已经尝试了几个小时而没有运气。我试图拟合线性函数(linearf)或幂律函数(plaw),其中我已经知道这些函数的斜率(b,我必须在本研究中保持它不变)。结果应该给出1.8左右的截距,这是我无法得到的。我必须做错事,但我不能指责它。有人知道如何解决这个问题吗?

提前谢谢!

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)
# >>> 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]
## >>>> return 3.4712954470408948e-41, it is wrong

1 个答案:

答案 0 :(得分:0)

我发现函数中存在错误:

应该是:

def plaw(x,a):

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

    return y

而不是

def plaw(a,x):

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

return y

愚蠢的错误。