将结果取决于先前结果的函数应用于numpy数组

时间:2019-04-18 13:09:57

标签: python loops numpy

我正在尝试将自定义函数应用于numpy数组,并且该函数的结果取决于先前的结果。具体来说,我正在尝试使用以下公式实现低通滤波器:

f(n) = f(n-1) + (a[n] - f(n-1)) * sampleRate / filterConst

我当然可以为f(n-1)保留一个状态变量,并遍历整个数组。我想知道是否有一种适当的方法可以做到这一点,它尊重numpy约定。

此外,我敢肯定,我的部分问题是我不知道该问什么。因此,如果您至少可以指出正确的方向,那将不胜感激。

P.S:我对此的一般解决方案感兴趣。我知道这种低通滤波器可能已经存在一些实现,对此我很感兴趣,但是我需要的是实现这种功能的通用方法。

谢谢。

3 个答案:

答案 0 :(得分:0)

如果仅循环遍历整个数组,而只是将当前索引输出到新容器中的同一索引,则应该保持numpy约定。

我不知道在傅立叶空间中做低通滤波器,然后反转fft会更容易吗?虽然这取决于您正在处理的数据。

答案 1 :(得分:0)

import numpy as np
from functools import reduce

def f(n): 
  return n*2

def reduce_func(n, a, sampleRate, filterConst):
  return f(n-1) + (a[n] - f(n-1)) * sampleRate / filterConst

a = np.array([1,2,3,4,5])
data = np.array([12,34,56,78,90])
sampleRate = 0.5
filterConst = 1.5

reduce(reduce_func, a)

答案 2 :(得分:0)

如果我了解您的方程式。我可以重构它。

res[n] = res[n-1]*(1-sampleRate/filterConst) + a*(sampleRate/filterConst)

以下内容仅经过快速测试。这是基于我所做的工作,我根据百分比和绝对值随时间变化的假设来预测价格。

import numpy as np

def do_filter(arr, sample_rate, filter_const, axis=-1):
"""  arr - a np array of floats your a
     sample_rate - a scalar
     filter_const - a scalar
     axis - int The axis to project along
"""  
    factor = sample_rate / filter_const
    cum_factor = np.full_like(arr, 1-factor).cumprod(axis=axis)
    # cum_factor is effectively a price index of factors
    amt = arr * factor / cum_factor
    # amt represents the values to add in deescalated by the price index.
    return amt.cumsum(axis=axis) * cum_factor
    # return the cumsum of the deescalated values in amt reescalated.

已经为价格构建了该对象,我无法使用它,因为周期因子可能为零。在这种情况下,它会崩溃。由于周期因素的期限相同,因此可能适合您的情况。

如果sample_rate(或filter_const)也是数组,则可以对其进行调整以使其与数组一起工作。