1 /** 2 * Copyright (c) 2023-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef LIBPANDABASE_UTILS_SEQUENCE_H 17 #define LIBPANDABASE_UTILS_SEQUENCE_H 18 19 #include <cmath> 20 #include "libpandabase/macros.h" 21 22 namespace ark { 23 class Sequence { 24 public: Add(double val)25 void Add(double val) 26 { 27 ASSERT(std::isfinite(val)); 28 if (empty_) { 29 mean_ = val; 30 variance_ = 0.0; 31 empty_ = false; 32 } else { 33 // Formula from "Incremental calculation of weighted mean and variance" by Tony Finch 34 // diff := x - mean 35 // incr := alpha * diff 36 // mean := mean + incr 37 // variance := (1 - alpha) * (variance + diff * incr) 38 // PDF available at https://fanf2.user.srcf.net/hermes/doc/antiforgery/stats.pdf 39 double diff = val - mean_; 40 double incr = DEFAULT_INCREMENTAL_FACTOR * diff; 41 mean_ += incr; 42 variance_ = (1.0 - DEFAULT_INCREMENTAL_FACTOR) * (variance_ + diff * incr); 43 } 44 } 45 GetMean()46 double GetMean() const 47 { 48 return mean_; 49 } 50 GetVariance()51 double GetVariance() const 52 { 53 return variance_; 54 } 55 GetStdDev()56 double GetStdDev() const 57 { 58 return sqrt(GetVariance()); 59 } 60 IsEmpty()61 bool IsEmpty() const 62 { 63 return empty_; 64 } 65 66 private: 67 bool empty_ {true}; 68 double mean_ {0.0}; 69 double variance_ {0.0}; 70 static constexpr double DEFAULT_INCREMENTAL_FACTOR = 0.3; 71 }; 72 } // namespace ark 73 #endif 74