Files
dragonpilot/common/util.py
Vehicle Researcher dd778596b7 openpilot v0.9.8 release
date: 2025-03-15T21:10:51
master commit: fb7b9c0f9420d228f03362970ebcfb7237095cf3
2025-03-18 10:05:17 -07:00

25 lines
785 B
Python

class MovingAverage:
def __init__(self, window_size: int):
self.window_size: int = window_size
self.buffer: list[float] = [0.0] * window_size
self.index: int = 0
self.count: int = 0
self.sum: float = 0.0
def add_value(self, new_value: float):
# Update the sum: subtract the value being replaced and add the new value
self.sum -= self.buffer[self.index]
self.buffer[self.index] = new_value
self.sum += new_value
# Update the index in a circular manner
self.index = (self.index + 1) % self.window_size
# Track the number of added values (for partial windows)
self.count = min(self.count + 1, self.window_size)
def get_average(self) -> float:
if self.count == 0:
return float('nan')
return self.sum / self.count