给定一个有序的numpy
浮点数组(从最小到最大),我需要确保元素之间的间距小于我调用的step
的任意浮点。你知道吗
这是我的代码,据我所知,它可以工作,但我想知道是否有一个更优雅的方式来做到这一点:
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四舍五入到最接近的二次方
3)将d除以m并重复结果m次
4)形成累计和
这是密码。技术说明:d的第一个元素不是差,而是“锚”,因此它等于数据的第一个元素。你知道吗
运行示例:
对于有序阵列:
那么
相关问题 更多 >
编程相关推荐