英文:
How to make a numpy.arange with incremental step size?
问题
我想处理数据,在已获取的数据量增加时,采集过程逐渐减慢。为了将索引值与估计的实时值关联起来,我估计一个增量函数,它近似表示任意两个相邻采集索引之间的实时时间差。
因此,我正在寻找一种有效的方法,从增量数组生成实际时间数组。
例如,假设增量是线性函数。然后,可以以递归方式计算任何时间值 t(i) 为 t(i) = (m i + b) + t(i-1),对于线性变化的时间增量 m i+b。
现在,我想要的是一个时间数组,而不是索引数组。一种非常方便的方法是类似于 numpy.arange 函数,具有增量步长,类似于:
np.arange(i_0, i_final, step=[m*i+b])
不幸的是,numpy 不支持这种方式。有现成的实现吗?如果没有,最简单的解决方案将是在索引数组上使用 for 循环,但由于数组可能很长,如果有更快的方法,我宁愿避免使用这种方式。
编辑:
一个非常简单的示例如下:
i t dt (从 i-1 到 i)
0 0
1 1 1
2 5 4
3 11 6
4 19 8
5 29 10
6 41 12
在这个示例中,增量步长将简单地为 dt(i) = 2i,用于从索引 i-1 到 i 的任何步骤。 (但通常步长是非整数。)
英文:
I want to process data, where the acquisition process slows down gradually as the amount of acquired data grows. In order to relate the index values to an estimated real time value, I estimate an increment function that approximates the real time delta between any two neighboring acquisition indices.
Hence, I am looking for an efficient way to generate the array of real times out of the array of increments.
As an example, let's assume a linear function for the increments. Then, any time value t(i) could be calculated in a recursive manner as t(i) = (m i + b) + t(i-1), for linearly changing time increments m i+b.
Now, I would like to have a time array instead of the index array. A very convenient way would be something like a numpy.arange function with incremental stepwidths; something like:
np.arange(i_0, i_final, step=[m*i+b])
Unfortunately, numpy doesn't support this. Is there a ready implementation at hand? If not, the simplest solution would be a for-loop over the index array, but since the arrays could be long, I would rather avoid this way, if there are faster ways.
EDIT:
A very simple example would be
i t dt (from i-1 to i)
0 0
1 1 1
2 5 4
3 11 6
4 19 8
5 29 10
6 41 12
where the increment step size would be simply dt(i) = 2i for any step from index i-1 to i. (However, the step size is usually non-integer.)
答案1
得分: 1
每个t
的值都等于初始值加上那一点之前的dt
的总和。因此,您可以使用np.cumsum
并将其添加到初始值以获得您的t
数组。为了确保您获得正确的初始值,请确保您的dt
数组从0开始。
import numpy as np
dt = np.array([0, 1, 4, 6, 8, 10, 12])
t0 = 0
t = t0 + np.cumsum(dt)
print(t)
输出:
array([ 0, 1, 5, 11, 19, 29, 41])
英文:
Each value of t
is equal to the initial value plus the sum of the dt
s up to that point. So, you can use np.cumsum
and add that to the initial value to get your t
array. To make sure you get the right initial value, make sure your dt
array starts at 0.
import numpy as np
dt = np.array([0, 1, 4, 6, 8, 10, 12])
t0 = 0
t = t0 + np.cumsum(dt)
print(t)
Output:
array([ 0, 1, 5, 11, 19, 29, 41])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论