gpt4 book ai didi

python - Numpy - 查找数据点的最大点和值

转载 作者:行者123 更新时间:2023-11-30 22:31:48 24 4
gpt4 key购买 nike

我刚刚开始学习 Numpy(和 Scipy)。我编写了一个程序来计算 f(x) 函数的绘图点。 (f(x) 无法明确给出,因为我必须对每个点进行数值求解方程。)我将这些值放入二维数组中:

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

我现在的目标是找到 f(x) 函数的最大值,并获取它的位置 xm 和它的值 f(xm)。当然我可以很容易地做到这一点,但这似乎是 NumPy 肯定有一个简单的功能。我发现的唯一东西是 numpy.amax,但它只返回每个轴的最大值。 (例如 numpy.amax([[1, 3, 2],[5, 7, 9]], axis=1) 返回 [3, 9]。)。

我有两个问题:

  1. 我是否采用了存储数据点的好方法,或者 NumPy/SciPy 中是否有特定的对象来执行此操作?

  2. 是否有内置的 NumPy/SciPy 函数来查找数据集的最大值?

    这是有问题的代码部分:

    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

最佳答案

您可以使用argmax功能:

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]

将 (6,9) 打印为具有 f(x) 最大值的 (x, f(x)) 对。请注意,argmax 仅返回第一次出现的最大值。如果f的最大值有可能多次出现并且您想要x的所有值,那么您可以这样做

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

关于python - Numpy - 查找数据点的最大点和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45699958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com