简体   繁体   中英

Numpy - Find maximum point and value of data points

I just started to learn Numpy (and Scipy). I wrote a program to compute plot points for an f(x) function. (f(x) can't be given explicitly as I have to numerically solve an equation for each point.) I put the values in a 2D array:

[[x1,    x2,    x3,    ...],
 [f(x1), f(x2), f(x3), ...]]

My aim is now to find the maxima of the f(x) function, and get both it's location xm and it's value f(xm). Of course I could easily do this, but this seems to be something NumPy surely has a simple function. The only thing I found is numpy.amax , but it only returns the maximum value at each axis. (eg numpy.amax([[1, 3, 2],[5, 7, 9]], axis=1) returns [3, 9].).

I have two questions:

  1. Did I took the good approach on storing the data points, or is there a specific object in NumPy/SciPy to do this?
  2. Is there a built-in NumPy/SciPy function to find the maxima of my dataset?

    This is the part of the code in question:

     def get_max(args): ti_0 = sp.pi / 2.0 + 1E-10 ti_max = sp.pi - 1E-10 iters = 10000 step = (ti_max - ti_0) / iters ti = ti_0 result = np.empty((2, iters), float_) #the dataset, aim is to find the point where ret_energy is maximal for i in range(0, iters): tret = find_return_time(x, ti) ret_energy = ekin(tret, ti) ret_time = tret / sp.pi result[i, 0] = ret_time result[i, 1] = ret_energy ti += step emax = None #emax = find_maximal_return_energy(result) #-> ??? return emax 

You can use the argmax function:

data = np.array([[2, 4, 6, 8],[1, 3, 9, 7]])
x = data[0,:]
f = data[1,:]
i = np.argmax(f)
print x[i], f[i]

prints (6,9) as the (x, f(x)) pair with the largest value of f(x). Note that argmax returns only the first occurrence of the maximum value. If there is a possibility that the maximum value of f occurs multiple times and you want all values of x , then you could do

maxvalue = np.max(f)
print x[f == maxvalue], maxvalue

1 - I think so

2 - argmax returns the index for the max value so you can retrieve that value and its corresponding x value.

idx = result[1].argmax()
xm = result[0,idx]
fxm = result[1,idx] 

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