fork download
  1. #include <iostream>
  2. #include <array>
  3. #include <vector>
  4. #include <cmath>
  5. #include <stdexcept>
  6.  
  7. /**
  8.  * Computes the pseudo-fusion value of a window of sensor readings.
  9.  *
  10.  * The window contains N values aggregated from 4 sensor streams.
  11.  * The fusion is computed as the geometric mean:
  12.  * result = (x1 * x2 * ... * xN) ^ (1/N)
  13.  *
  14.  * To avoid overflow from direct multiplication, we use the log-sum-exp trick:
  15.  * result = exp((1/N) * sum(log(xi)))
  16.  *
  17.  * @param window Flat array of N aggregated sensor values (each aggregated from 4 streams)
  18.  * @return The pseudo-fusion value (geometric mean)
  19.  */
  20. double computePseudoFusion(const std::vector<double>& window) {
  21. const size_t N = window.size();
  22.  
  23. if (N <= 0) {
  24. throw std::invalid_argument("Window must contain at least one value.");
  25. }
  26.  
  27. double log_sum = 0.0;
  28.  
  29. for (size_t i = 0; i < N; i++) {
  30. if (window[i] <= 0.0) {
  31. throw std::domain_error(
  32. "All sensor values must be positive for geometric mean computation. "
  33. "Got non-positive value at index " + std::to_string(i)
  34. );
  35. }
  36. log_sum += std::log(window[i]);
  37. }
  38.  
  39. return std::exp(log_sum / static_cast<double>(N));
  40. }
  41.  
  42. int main() {
  43.  
  44.  
  45. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Standard output is empty