内插python数组以最小化元素之间的最大差异 [英] interpolate python array to minimize maximum difference between elements

查看:133
本文介绍了内插python数组以最小化元素之间的最大差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

插值一维数组以使元素之间的最大差异最小化的简洁易读的方法是什么?

What is a concise and readable way of interpolating a 1D array such that the maximum difference between elements is minimized?

例如,如果我有一个数组[4 9 13 25],并且允许我再增加1个数字,以便最小化元素之间的最大差值,那么我会在13到25之间插入一个19(现在最大差值为6)而不是12).

For instance, if I had the array [4 9 13 25] and I was allowed to add 1 more number in order to minimize the maximum difference between elements I would insert a 19 between 13 and 25 (max difference is now 6 rather than 12).

当然,一个好的ole'for loop可以完成它,但是对于后代,有没有比下面更详细的方法了?

Of course a good ole' for loop will get it done, but for posterity is there a less verbose approach than below?

# current array
nums = np.array([4.0, 9.0, 13.0, 25.0])
# size of new array
N=10

# recursively find max gap (difference) and fill it with a mid point    
for k in range(N-len(nums)):
    inds = range(len(nums))
    # get the maximum difference between two elements
    max_gap = np.argmax(np.diff(nums))
    # put a new number that's equidistant from the two element values
    new_num = np.interp(np.mean([inds[max_gap],inds[max_gap+1]]), inds, nums)
    nums = np.insert(nums, max_gap+1, new_num)
    print nums

此示例对一维数组进行插值,填充最大差异为的区域:

This example interpolates the 1D array, filling regions where the greatest difference was:

[  4.   9.  13.  19.  25.]
[  4.   9.  13.  16.  19.  25.]
[  4.   9.  13.  16.  19.  22.  25.]
[  4.    6.5   9.   13.   16.   19.   22.   25. ]
[  4.    6.5   9.   11.   13.   16.   19.   22.   25. ]
[  4.    6.5   9.   11.   13.   14.5  16.   19.   22.   25. ]

修改1: 正如评论所建议的,在可读性,效率和准确性之间要进行权衡.在这三个属性中,对我来说最重要的是可读性.我仍然对上述算法的所有改进都给出+1,因为这是一个普遍的问题,任何改进这三个属性中任何一个的答案都对某人有益,如果以后不是我的话.

edit 1: As comments suggest, there is a trade-off between readability, efficiency, and accuracy. Of these three attributes, for me the most important is readability. I still give +1 for any and all improvements to my above algorithm though since it is a general problem and any answer that improves either of those three attributes is beneficial to someone if not me later on.

推荐答案

如果,数组较小,可读性比效率更重要,我建议:

If the array is small and readability is more important than efficiency I suggest:

  nums = [4., 9., 13., 25]
  N = 10
  while len(nums) < N:
      pos = np.argmax(np.diff(nums))   # where maximum difference is
      nums.insert(pos+1, (nums[pos+1] + nums[pos]) / 2.)  #introduce value

当然,这受到了前面提到的问题的困扰,即这可能不是在运行结束时以点之间的最小差异进行插值的最有效方法.

Of couse, this suffers from the problems already mentioned that probably this is not the most efficient way of interpolating with the minimum differences between the points at the end of the run.

这篇关于内插python数组以最小化元素之间的最大差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆