简体   繁体   中英

Find the index of the last negative value of an increasing function

I have some increasing function and a range of values, I would like to find the last index for which this function is still negative, as a minimal working example we have:

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

this works, and for this example would be a fine solution. However: For my example, the computation time of evaluating the function f is more like 1 minute so doing this it this way is very cumbersome. Moreover I already have a guess for where the value n should be. I can write my own program looking for the value by mimicking some algorithm for finding roots of functions but I was wondering if there was some easy built-in way to do this?

You could use bisect from the standard lib (not the scipy one). You just need to trick it into believing it is dealing with an array.

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

You can also restrict to a subrange:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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