Search code examples
pythonlistfunctioninverse

How to "inverse" list in python? Like Inverse Function


I have some complicated function called dis(x), which returns a number.

I am making two lists called let's say ,,indices'' and ,,values''. So what I do is following:

for i in np.arange(0.01,4,0.01):
    values.append(dis(i))
    indices.append(i)

So i have following problem, how do i find some index j (from indices), which dis(j) (from values) is closest to some number k.


Solution

  • Combination of enumerate and the argmin function in numpy will do the job for you.

    import numpy as np
    
    values = []
    indices = []
    def dis(x):
        return 1e6*x**2
    
    for i in np.arange(0.01,4,0.01):
        values.append(dis(i))
        indices.append(i)
    target = 10000
    
    
    closest_index = np.argmin([np.abs(x-target) for x in values])
    print(closest_index)