【问题标题】:Find two zeros of a function with Python用 Python 查找函数的两个零
【发布时间】:2017-11-22 19:05:41
【问题描述】:

我有一个函数 f(x),我知道它在一个区间内有两个零,我需要计算两个 x 值以使函数与 0 交叉。

我经常用

import scipy.optimize as opt
opt.brentq(f, xmin, xmax)

但问题是,如果函数的区间有一个0,这个方法是有效的,而且要知道在哪里分成两部分并不是很简单。

函数的评估也很耗时...

【问题讨论】:

  • 是连续函数吗?
  • 函数在区间内部是否有唯一的最小值/最大值?如果是这样,您可以首先找到该极值的位置,例如通过golden section search,然后使用它将您的区间分成两部分,每部分包含一个根。
  • 上述两个 cmets 的较短版本:请向我们提供有关您的功能的更多信息。你怎么知道它正好有两个零?

标签: python numpy math optimization scipy


【解决方案1】:

我认为一个好的方法是在搜索零之前通过采样 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] 中的所有零。 请记住,此算法很耗时,但可以胜任。

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 2021-07-24
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多