123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- #ifndef MATHUTIL_H
- #define MATHUTIL_H
- #include <QVector>
- #include <QtMath>
- #include <limits>
- namespace Helper {
- static double minvec(const QVector<double> &vec)
- {
- double val = std::numeric_limits<double>::min();
- for (int i = 0; i < vec.count(); ++i) {
- if (i == 0) {
- val = vec.at(i);
- } else if (val > vec.at(i)) {
- val = vec.at(i);
- }
- }
- return val;
- }
- static double maxvec(const QVector<double> &vec)
- {
- double val = std::numeric_limits<double>::max();
- for (int i = 0; i < vec.count(); ++i) {
- if (i == 0) {
- val = vec.at(i);
- } else if (val < vec.at(i)) {
- val = vec.at(i);
- }
- }
- return val;
- }
- /// 均值
- static double mean(const QVector<double> &vec)
- {
- if (vec.count() == 0) {
- return 0;
- }
- double sum = 0;
- for (auto v : vec) {
- sum += v;
- }
- return sum / vec.count();
- }
- /// 标准差
- static double standardDeviation(const QVector<double> &vec)
- {
- return qSqrt(standardDeviation(vec));
- }
- static std::pair<double, double> meanAndStandardDeviation(const QVector<double> &vec)
- {
- if (vec.count() == 0) {
- return std::make_pair(0, 0);
- }
- double meanVal = mean(vec);
- double sum = 0;
- for (auto v : vec) {
- sum += qPow(v - meanVal, 2.0);
- }
- return std::make_pair(meanVal, sum / vec.count());
- }
- /// 方差
- static double variance(const QVector<double> &vec)
- {
- if (vec.count() == 0) {
- return 0;
- }
- double meanVal = mean(vec);
- double sum = 0;
- for (auto v : vec) {
- sum += qPow(v - meanVal, 2.0);
- }
- return sum / vec.count();
- }
- static void Standardization(QVector<QVector<double>> &v)
- {
- double Avg, STD;
- for (int i = 0; i < v.size(); i++) {
- Avg = mean(v[i]);
- STD = standardDeviation(v[i]);
- for (int j = 0; j < v[i].size(); j++) {
- v[i][j] = (v[i][j] - Avg) / STD;
- }
- }
- }
- static double cov(QVector<double> vA, QVector<double> vB)
- {
- double total;
- for (int i = 0; i < vA.size(); i++) {
- total += vA[i] * vB[i];
- }
- return (total / vA.size());
- }
- static QVector<QVector<double>> Covarience(QVector<QVector<double>> features)
- {
- QVector<QVector<double>> covMatrix;
- QVector<double> temp;
- for (int i = 0; i < features.size(); i++) {
- for (int j = 0; j < features.size(); j++) {
- temp.push_back(cov(features[i], features[j]));
- }
- covMatrix.push_back(temp);
- temp.clear();
- }
- return covMatrix;
- }
- } // namespace Helper
- #endif // MATHUTIL_H
|