繁体   English   中英

查找递增函数的最后一个负值的索引

[英]Find the index of the last negative value of an increasing function

我有一些递增的函数和一系列值,我想找到该函数仍为负的最后一个索引,作为最小的工作示例,我们有:

def f(x):
    return x-7
x_range = np.linspace(-10,10,num=1000)
n = next(n for n, x in enumerate(x_range) if f(x) < 0) - 1

这行得通,对于这个例子来说将是一个很好的解决方案。 但是:在我的示例中,评估函数f的计算时间更像是1分钟,因此以这种方式这样做非常麻烦。 而且我已经猜到了值n应该在哪里。 我可以编写自己的程序,方法是模仿某种算法来寻找函数根,以寻找价值,但我想知道是否存在一些简单的内置方法来实现?

您可以从标准库(而不是scipy one)中使用bisect 您只需要欺骗它就可以认为它正在处理数组。

>>> import numpy as np
>>> import bisect
>>> 
>>> class fake_array:
...     def __init__(self, f, rng):
...         self.f, self.rng = f, rng
...     def __getitem__(self, x):
...         return self.f(self.rng[x])
...     def __len__(self):
...         return len(self.rng)
... 
>>> def f(x):
...     return x-7
... 
>>> x_range = np.linspace(-10,10,num=1000)
>>>
>>> bisect.bisect_left(fake_array(f, x_range), 0) - 1
849

您还可以限制为一个子范围:

>>> bisect.bisect_left(fake_array(f, x_range), 0, 800, 900) - 1
849

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM