• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2023 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 
21 namespace panda {
22 class Sequence {
23 public:
Add(double val)24     void Add(double val)
25     {
26         if (empty_) {
27             mean_ = val;
28             variance_ = 0.0;
29             empty_ = false;
30         } else {
31             // Formula from "Incremental calculation of weighted mean and variance" by Tony Finch
32             // diff := x - mean
33             // incr := alpha * diff
34             // mean := mean + incr
35             // variance := (1 - alpha) * (variance + diff * incr)
36             // PDF available at https://fanf2.user.srcf.net/hermes/doc/antiforgery/stats.pdf
37             double diff = val - mean_;
38             double incr = DEFAULT_INCREMENTAL_FACTOR * diff;
39             mean_ += incr;
40             variance_ = (1.0 - DEFAULT_INCREMENTAL_FACTOR) * (variance_ + diff * incr);
41         }
42     }
43 
GetMean()44     double GetMean() const
45     {
46         return mean_;
47     }
48 
GetVariance()49     double GetVariance() const
50     {
51         return variance_;
52     }
53 
GetStdDev()54     double GetStdDev() const
55     {
56         return sqrt(GetVariance());
57     }
58 
IsEmpty()59     bool IsEmpty() const
60     {
61         return empty_;
62     }
63 
64 private:
65     bool empty_ {true};
66     double mean_ {0.0};
67     double variance_ {0.0};
68     static constexpr double DEFAULT_INCREMENTAL_FACTOR = 0.3;
69 };
70 }  // namespace panda
71 #endif
72