0

我有一小段代码会产生错误消息(我认为是因为数学公式)。有人知道为什么吗?

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
from scipy.integrate import quad
n = 3
x = np.array([2.1,2.2,2.3,2.4])
y = np.array([0.9,2.1,3.2,17.9])
def func(x, a, b):
    b1 = n*quad(x[n]*np.log(y[n]), 1, n) - quad(x[n], 1, n)*quad(np.log(y[n]), 1, n)
    b2 = n*quad(x[n]**2, 1, n) - (quad(x[n], 1, n))**2
    b = b1 / b2
    a = np.exp(1/n+(quad(np.log(y[n]), 1, n) - b(quad(x[n], 1, n))))
    return a*np.exp(b*x)
popt, pcov = curve_fit(func, x, y)
print popt
plt.plot(x, y)
plt.grid(True)
plt.show()

错误日志:

Traceback (most recent call last):
  File "F:\py-IAT\Laktat.py", line 20, in <module>
    popt, pcov = curve_fit(func, x, y)
  File "C:\Python27\lib\site-packages\scipy\optimize\minpack.py", line 506, in curve_fit
    res = leastsq(func, p0, args=args, full_output=1, **kw)
  File "C:\Python27\lib\site-packages\scipy\optimize\minpack.py", line 348, in leastsq
    m = _check_func('leastsq', 'func', func, x0, args, n)[0]
  File "C:\Python27\lib\site-packages\scipy\optimize\minpack.py", line 14, in _check_func
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
  File "C:\Python27\lib\site-packages\scipy\optimize\minpack.py", line 418, in _general_function
    return function(xdata, *params) - ydata
  File "F:\py-IAT\Laktat.py", line 15, in func
    b1 = n*quad(x[n]*np.log(y[n]), 1, n) - quad(x[n], 1, n)*quad(np.log(y[n]), 1, n)
  File "C:\Python27\lib\site-packages\scipy\integrate\quadpack.py", line 247, in quad
    retval = _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points)
  File "C:\Python27\lib\site-packages\scipy\integrate\quadpack.py", line 312, in _quad
    return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
quadpack.error: quad: first argument is not callable

谢谢!

4

2 回答 2

1

根据docs, to 的第一个参数quad应该是要集成的函数。你有一个表达式而不是函数。要解决这个问题,您可以尝试在quad调用中引入匿名函数:

b1 = n*quad(lambda n:x[n]*np.log(y[n]), 1, n) - quad(lambda n:x[n], 1, n) * \
     quad(lambda n:np.log(y[n]), 1, n)

这是未经测试的,但它应该工作。

于 2014-02-26T14:52:08.063 回答
1

Kevin 指出 quad 的第一个参数应该是一个函数,而您输入的是一个数字。我建议创建一个函数

def newfunc(x, y, n):
  # Insert appropriate processing here
  return x[n]*np.log(y[n])

现在将 newfunc 作为quad 的第一个参数,并在调用序列中使用适当的参数。

请注意,对 quad 的其他调用将需要类似的修改。

于 2014-02-26T14:58:48.403 回答