代码之家  ›  专栏  ›  技术社区  ›  hamster on wheels

快速将阵列分配给等长的n个存储单元

  •  2
  • hamster on wheels  · 技术社区  · 7 年前

    0.0 10.0

    我想分配 arr 5

    等长是指bin间隔为 [0.0, 2.0), [2.0, 4.0), [4.0, 6.0), [6.0, 8.0), [8.0, 10.0] .

    问题是最后一个间隔与其他间隔不同。

    测试:

    import numpy as np
    # Things we know and can pre-calculate
    n_bins = 5
    minimal = 0.0  
    maximal = 10.0
    reciprocal_bin_length = n_bins / (maximal - minimal)
    
    # Let's say the stream gives 1001 numbers every time.
    data = np.arange(1001)/100
    
    norm_data = (data - minimal) * reciprocal_bin_length
    norm_data = norm_data.astype(int)
    print(norm_data.max())
    print(norm_data.min())
    

    5
    0
    

    箱子索引应该是0、1、2、3或4,但不是5。

    2 回复  |  直到 7 年前
        1
  •  3
  •   willeM_ Van Onsem    7 年前

    穷人的解决方案 “可能是计算 minimum 在您的阵列之间 norm_data nbins-1 :

    norm_data = np.minimum(norm_data,nbins-1)
    

    所以所有 5 4 120.0 也将在箱子4)中结束。

        2
  •  0
  •   hamster on wheels    7 年前

    import numpy as np
    # Things we know and can pre-calculate
    n_bins = 5
    minimal = 0.0  
    maximal = 10.0
    approx = 1.001  # <-- this is new
    reciprocal_bin_length = n_bins / (maximal*approx - minimal)
    
    # Let's say the stream gives 1001 numbers every time.
    data = np.arange(1001)/100
    
    # can use numexpr for speed.
    norm_data = (data - minimal) * reciprocal_bin_length
    norm_data = norm_data.astype(int)
    print(norm_data.max())
    print(norm_data.min())