代码之家  ›  专栏  ›  技术社区  ›  normanius

退化寻根问题:得到f(x)>0的第一个值

  •  0
  • normanius  · 技术社区  · 3 年前

    给定一个函数 f(x) 所有值都为零 x 小于临界值 c ,值为非零 x>c 。

    我想近似临界值 c 使用优化方法。因为函数 f(x) 是昂贵的,我想尽可能少地计算它。因此,计算 f(x) 用于预定义的值列表 x 是不可行的。

    想想下面这样一个函数,有关键点 a=1.4142

    def func(x):
        return max(x**2 - 2, 0) if x > 0 else 0
    

    我会使用一些自定义的平分函数来实现这一点。然而,我想知道这个“退化”的根查找问题是否可以使用SciPy或NumPy中的现有函数来解决。我试验过 scipy.optimize.root_scalar 。但是,它似乎不支持像上面这样的功能。

    from scipy.optimize import root_scalar
    root_scalar(func, bracket=[-6, 8])
    # Yields an error: f(a) and f(b) must have different signs.
    
    0 回复  |  直到 3 年前
        1
  •  3
  •   Nick ODell    3 年前

    从技术上讲,只要x<1.414在该函数中是根。如果你想使用根查找器,你需要使它成为一个有效的根查找问题。我建议从函数的输出中减去一个非常小的值:

    from scipy.optimize import root_scalar
    import math
    wrapper = lambda func: lambda *args: func(*args) - math.ulp(0)
    root_scalar(wrapper(func), bracket=[-6, 8])
    

    这是通过从函数中减去一个ULP(单位在最后一位,可以加或减的最小值)来实现的。这使得它对于所有x<1.414,并且对于所有x>1.414.在一台64位浮点运算的计算机上,这意味着它减去了5*10 -324 从每个结果来看,这会稍微移动根的位置,但不会移动太多。

        2
  •  1
  •   normanius    3 年前

    这只是为了提供一个适用于所示示例的“自定义”平分方法。然而,我仍然建议使用公认的答案。

    def bisect(func, x_min, x_max, x_func=None,
               tol=None, iter_max=None, **kwargs):
        y_min = func(x_min, **kwargs)
        if y_min > 0:
            msg = "Warning: no solution as y_min>0, with x_min=%f."
            print(msg % x_min)
            return x_min
        y_max = func(x_max, **kwargs)
        if y_max <= 0:
            msg = "Warning: no solution as y_max<=0, with x_max=%f."
            print(msg % x_max)
            return x_max
        if tol is None and iter_max is None:
            tol = 1e-7
        if x_func is None:
            x_func = lambda x0, x1: (x1+x0)/2
        
        from itertools import count, islice
        x_last = np.infty
        for cnt in islice(count(), iter_max):
            x_new = x_func(x_min, x_max)
            y_new = func(x_new, **kwargs)
            if y_new<=0:
                x_min = x_new
            else:
                x_max = x_new
            if (tol is not None) and abs(x_last - x_new) < tol:
                break
            x_last = x_new
        return x_min if y_new>0 else x_max
    
    def func(x):
        return max(x**2 - 2, 0) if x > 0 else 0
    
    ret = bisect(func, x_min=-6, x_max=8)
    print(ret)
    

    有趣的是 bisect() 看起来比 root_scalar 这个基本函数类型的方法 func(x) 。但我预计这种优势会在更复杂的函数中消失。

    %timeit bisect(func, x_min=-6, x_max=8, iter_max=None, tol=1e-7)
    # 46.3 µs ± 1.96 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
    
    %timeit root_scalar(wrapper(func), bracket=[-6, 8], xtol=1e-7)
    # 84.6 µs ± 6.29 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
    
    # Test that the results are equivalent:
    x1 = bisect(func, x_min=-6, x_max=8, iter_max=None, tol=1e-7)
    x2 = root_scalar(wrapper(func), bracket=[-6, 8], xtol=1e-7).root
    assert abs(x2-x1) < 1e-7
    # 2.9078300656237843e-08