Skip to main content
 首页 » 编程设计

python之将元素插入到 numpy 数组中,以便最小间距是任意的

2025年05月04日20mq0036

给定一个有序的 numpy float 组(从最小值到最大值),我需要确保元素之间的间距小于我称为 step 的任意 float 。

这是我的代码,据我所知它是有效的,但我想知道是否有更优雅的方法来做到这一点:

import numpy as np 
 
def slpitArr(arr, step=3.): 
    """ 
    Insert extra elements into array so that the maximum spacing between 
    elements is 'step'. 
    """ 
    # Keep going until no more elements need to be added 
    while True: 
        flagExit = True 
        for i, v in enumerate(arr): 
            # Catch last element in list 
            try: 
                if abs(arr[i + 1] - v) > step: 
                    new_v = (arr[i + 1] + v) / 2. 
                    flagExit = False 
                    break 
            except IndexError: 
                pass 
        if flagExit: 
            break 
        # Insert new element 
        arr = np.insert(arr, i + 1, new_v) 
 
    return arr 
 
 
aa = np.array([10.08, 14.23, 19.47, 21.855, 24.34, 25.02]) 
 
print(aa) 
print(slpitArr(aa)) 

结果是:

[10.08  14.23  19.47  21.855 24.34  25.02 ] 
[10.08  12.155 14.23  16.85  19.47  21.855 24.34  25.02 ] 

请您参考如下方法:

这是一个一次性解决方案

1) 计算连续点之间的差异d

2) ceil-逐步划分d得到m

2a) 可选地将 m 舍入到最接近的 2 的幂

3) 将d 除以m 并将结果重复m 次

4)形成累加和

这是代码。技术说明:d的第一个元素不是difference而是“anchor”,所以它等于data的第一个元素。

def fill(data, step, force_power_of_two=True): 
    d = data.copy() 
    d[1:] -= data[:-1] 
    if force_power_of_two: 
        m = 1 << (np.frexp(np.nextafter(d / step, -1))[1]).clip(0, None) 
    else: 
        m = -(d // -step).astype(int) 
    m[0] = 1 
    d /= m 
    return np.cumsum(d.repeat(m)) 

样本运行:

>>> inp 
array([10.08 , 14.23 , 19.47 , 21.855, 24.34 , 25.02 ]) 
>>> fill(inp, 3) 
array([10.08 , 12.155, 14.23 , 16.85 , 19.47 , 21.855, 24.34 , 25.02 ])