[英]Moving Standard Deviation in Python WITHOUT using built-in functions
我正在尝试计算数据集的移动标准差数组。 我有我原来的 position 和时间数据,也找到了这个 position 数据的移动平均数组。 我已经看到了 python 中用于计算滚动平均值和标准偏差的各种内置函数。 我犹豫要不要使用它,因为我必须设置一个参数是进程的方向 window(向前:当前时间到 window 长度,居中:window 长度以当前时间为中心,向后:window 长度到当前时间)。 这会影响我必须在每个数据点使用的数据范围。 下面是我计算移动平均误差的代码。
def MA(pos, t, processWindow, positionTolerance, calculationDirection, figNum):
#pos and t are position and time lists, processWindow is given in seconds, but represent
the length of the window
N = len(t)
windowLength = processWindow*1000 #process window given in seconds---> length becomes 50
i = 0
MA = []
while i < N:
if calculationDirection == 'Forward':
startPos = i
endPos = int(i+ windowLength)
elif calculationDirection == 'Centered':
startPos = int(i-windowLength/2)
endPos = int(i+windowLength/2)
elif calculationDirection == 'Backward':
startPos = int(i-windowLength)
endPos = i
window = pos[startPos : endPos]
window_average = round(sum(window) / windowLength, 4)
MA.append(window_average)
i+=1
return MA
MA
返回一个列表,其中包含每个 position 点的移动平均值。 有没有办法以类似的方式计算移动标准偏差?
有没有办法以类似的方式计算移动标准偏差?
只需更改window_average =...
中的公式:
import math
def std(data: list) -> float:
N = len(data)
mean = sum(data) / N
variance = sum((x - mean)**2 for x in data) / (N - 1)
return math.sqrt(variance)
def moving_std(pos, t, processWindow, positionTolerance, calculationDirection, figNum):
# Same thing as in your `MA` function...
...
while ...:
window = pos[startPos : endPos]
window_std = std(window) # new formula
MA.append(window_std)
# go on with the loop...
return MA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.