vulp  2.3.0
low_pass_filter.h
Go to the documentation of this file.
1 // SPDX-License-Identifier: Apache-2.0
2 // Copyright 2022 Stéphane Caron
3 
4 #pragma once
5 
6 #include <stdexcept>
7 #include <string>
8 
9 #include "vulp/exceptions/FilterError.h"
10 
11 namespace vulp::utils {
12 
13 using vulp::exceptions::FilterError;
14 
24 inline double low_pass_filter(double prev_output, double cutoff_period,
25  double new_input, double dt) {
26  // Make sure the cutoff period is not too small
27  if (cutoff_period <= 2.0 * dt) {
28  auto message =
29  std::string("[low_pass_filter] Cutoff period ") +
30  std::to_string(cutoff_period) +
31  " s is less than 2 * dt = " + std::to_string(2.0 * dt) +
32  " s, causing information loss (Nyquist–Shannon sampling theorem)";
33  throw FilterError(message);
34  }
35 
36  // Actual filtering ;)
37  const double alpha = dt / cutoff_period;
38  return prev_output + alpha * (new_input - prev_output);
39 }
40 
41 } // namespace vulp::utils
Utility functions.
Definition: __init__.py:1
double low_pass_filter(double prev_output, double cutoff_period, double new_input, double dt)
Low-pass filter as an inline function.