我认为一个好的方法是在搜索零之前通过采样 f 来预处理零的搜索。在该预处理过程中,您评估 f 以检测函数的符号是否已更改。
def preprocess(f,xmin,xmax,step):
first_sign = f(xmin) > 0 # True if f(xmin) > 0, otherwise False
x = xmin + step
while x <= xmax: # This loop detects when the function changes its sign
fstep = f(x)
if first_sign and fstep < 0:
return x
elif not(first_sign) and fstep > 0:
return x
x += step
return x # If you ever reach here, that means that there isn't a zero in the function !!!
使用此功能,您可以将初始间隔分成几个较小的间隔。例如:
import scipy.optimize as opt
step = ...
xmid = preprocess(f,xmin,max,step)
z0 = opt.brentq(f,xmin,xmid)
z1 = opt.brentq(f,xmid,xmax)
根据您使用的函数f,您可能需要将您的区间分隔为两个以上的子区间。只需像这样遍历 [xmin,xmax] :
x_list = []
x = x_min
while x < xmax: # This discovers when f changes its sign
x_list.append(x)
x = preprocess(f,x,xmax,step)
x_list.append(xmax)
z_list = []
for i in range(len(x_list) - 1):
z_list.append(opt.brentq(f,x_list[i],x_list[i + 1]))
最后,z_list 包含给定区间 [xmin,xmax] 中的所有零。
请记住,此算法很耗时,但可以胜任。