使用brentq和两个数据列表

时间:2014-12-28 23:34:56

标签: python scipy

我正在尝试查找由以下数据定义的行的根:

x = [1,2,3,4,5]
y = [-2,4,6,8,4]

我已经开始使用插值但我被告知我可以使用brentq函数。如何从两个列表中使用brentq?我认为它需要连续的功能。

1 个答案:

答案 0 :(得分:0)

正如documentation of brentq所说,第一个参数必须是连续函数。因此,您必须首先从数据中生成一个函数,该函数将为传递给它的每个参数返回一个值。您可以使用interp1d

执行此操作
import numpy as np
from scipy.interpolate import interp1d
from scipy.optimize import brentq
x, y = np.array([1,2,3,4,5]), np.array([-2,4,6,8,4])
f = interp1d(x,y, kind='linear')  # change kind to something different if you want e.g. smoother interpolation
brentq(f, x.min(), x.max()) # returns: 1.33333

您还可以使用样条线生成brentq所需的连续函数。