插值一维数组以使元素之间的最大差异最小化的简洁且可读的方法是什么?
例如,如果我有数组 [4 9 13 25] 并且允许我再添加 1 个数字以最小化元素之间的最大差异,我会在 13 和 25 之间插入 19 (最大差异现在是 6 而不是 12 )。
当然,一个好的 ole' for 循环可以完成它,但是对于后代来说,有没有比下面更简洁的方法呢?
# 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
此示例对一维数组进行插值,填充差异最大的区域:
[ 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. ]
edit 1:正如评论所暗示的,可读性、效率和准确性之间需要权衡。在这三个属性中,对我来说最重要的是可读性。我仍然对上述算法的任何和所有改进给予+1,因为这是一个普遍问题,任何改进这三个属性中的任何一个的答案都会对某人(如果不是我以后)有益。