簡體   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