You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于非均匀NumPy网格生成更均匀密集网格的Python方案问询

非均匀实验网格重采样的Python实现方案

你需要的是保留原网格所有点、在稀疏区域补点、最终生成指定点数且均匀性最优网格的功能,目前没有直接开箱即用的工具包,但可以基于NumPy手动实现,核心逻辑是根据原网格的区间密度分配新增点的数量,以下是具体方案:

一、核心思路

  • 计算原网格相邻点的间距,间距越大的稀疏区域分配更多新增点
  • 总新增点数 = 指定输出点数 - 原网格点数,按间距占比分配到各个区间
  • 在每个区间内均匀插入对应数量的点,确保原坐标完全保留
  • 处理浮点精度导致的重复点,最终保证输出点数严格匹配指定值

二、实现代码

import numpy as np

def resample_grid(initial_grid: np.array, num_out_points: int) -> np.array:
    # 确保输入网格有序(实验数据通常有序,做冗余保障)
    initial_grid = np.sort(initial_grid)
    n_initial = len(initial_grid)
    
    if num_out_points <= n_initial:
        # 指定点数少于原点数时,直接返回原网格(保留所有原始坐标)
        return initial_grid.copy()
    
    # 计算相邻点间距与总间距
    gaps = np.diff(initial_grid)
    total_gap = gaps.sum()
    num_add = num_out_points - n_initial
    
    # 按间距占比分配每个区间的新增点数,修正总和偏差
    add_counts = np.round((gaps / total_gap) * num_add).astype(int)
    diff = num_add - add_counts.sum()
    if diff != 0:
        # 差值分配给间距最大的区间,保证均匀性最优
        largest_gap_indices = np.argsort(gaps)[-abs(diff):]
        add_counts[largest_gap_indices] += np.sign(diff)
    
    # 生成新网格
    new_grid = []
    for i in range(n_initial):
        new_grid.append(initial_grid[i])
        if i < n_initial - 1 and add_counts[i] > 0:
            # 在当前区间均匀插入指定数量的点
            step = gaps[i] / (add_counts[i] + 1)
            insert_points = initial_grid[i] + step * np.arange(1, add_counts[i] + 1)
            new_grid.extend(insert_points)
    
    # 去重、排序,处理浮点精度导致的重复点
    new_grid = np.unique(np.array(new_grid))
    # 若去重后点数不足,补在当前最大间距的区间中点
    while len(new_grid) < num_out_points:
        gaps_new = np.diff(new_grid)
        max_gap_idx = np.argmax(gaps_new)
        insert_point = (new_grid[max_gap_idx] + new_grid[max_gap_idx + 1]) / 2
        new_grid = np.insert(new_grid, max_gap_idx + 1, insert_point)
    
    return np.sort(new_grid)

三、代码特性

  • 完全保留原网格的所有坐标,无丢失或篡改
  • 新增点优先分配到稀疏区域,最小化区间长度的均值与方差
  • 结果稳定无随机性,输出点数严格匹配指定值
  • 处理浮点精度问题导致的重复点,保证网格的有效性

四、测试示例

用你提供的实验数据测试:

x = np.array([53.821593,  53.85265044, 53.88373501, 53.91484627, 53.94598466, 53.97714997, 54.00834218, 54.03956172, 54.07080797, 54.10208155, 54.13338225, 54.16471028,
 54.19606522, 54.2274477])

# 生成30个点的新网格
new_x = resample_grid(x, 30)
print(f"原点数:{len(x)}, 新点数:{len(new_x)}")
print(new_x)

内容的提问来源于stack exchange,提问作者twistfire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:55:22