swift
Loading...
Searching...
No Matches
mathutils.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <cmath>
7#include <cstdlib>
8#include <limits>
9
10#include <QTime>
11#include <QtGlobal>
12
13#include "misc/math/constants.h"
14#include "misc/verify.h"
15
16namespace swift::misc::math
17{
18 double CMathUtils::round(double value, int digits)
19 {
20 // gosh, is there no Qt method for this??? It's year 2013
21 double intpart {};
22 double fractpart = modf(value, &intpart);
23 if (epsilonZeroLimits(fractpart))
24 {
25 return value;
26 } // do not mess any "integers" to the worse
27 const double m = pow(10.0, digits);
28 const qint64 ri = qRound64(value * m); // do not loose any range here
29 const double rv = static_cast<double>(ri) / m;
30 return rv;
31 }
32
33 double CMathUtils::roundEpsilon(double value, double epsilon)
34 {
35 if (epsilonZeroLimits(epsilon))
36 {
37 return value;
38 } // avoid division by 0
39 double intpart {};
40 double fractpart = modf(value, &intpart);
41 if (epsilonZeroLimits(fractpart))
42 {
43 return value;
44 } // do not mess any "integers" to the worse
45 const double roundValue = value / epsilon;
46 const qint64 ri = qRound64(roundValue);
47 const double rv = static_cast<double>(ri) * epsilon; // do not loose any range here
48 return rv;
49 }
50
51 bool CMathUtils::epsilonEqual(float v1, float v2, float epsilon) { return qAbs(v1 - v2) <= epsilon; }
52
53 bool CMathUtils::epsilonEqual(double v1, double v2, double epsilon) { return qAbs(v1 - v2) <= epsilon; }
54
55 double CMathUtils::deg2rad(double degree) { return degree * c_pi / 180.0; }
56
57 double CMathUtils::rad2deg(double radians) { return radians * 180.0 / c_pi; }
58
59 double CMathUtils::normalizeDegrees180(double degrees)
60 {
61 const double result = CMathUtils::normalizeDegrees360(degrees + 180.0) - 180.0;
62 return (result <= -180.0) ? 180.0 : result; // -180->180
63 }
64
65 double CMathUtils::normalizeDegrees360(double degrees)
66 {
67 const double result = std::fmod(degrees, 360.0);
68 return (result >= 0.0) ? result : result + 360.0;
69 }
70
72 {
73 thread_local QRandomGenerator rng(QRandomGenerator::global()->generate());
74 return rng;
75 }
76
77 int CMathUtils::randomInteger(int low, int high)
78 {
79 Q_ASSERT_X(high < INT_MAX, Q_FUNC_INFO, "Cannot add 1");
80 return randomGenerator().bounded(low, high + 1);
81 }
82
83 double CMathUtils::randomDouble(double max)
84 {
85 constexpr int MAX(std::min(RAND_MAX - 1, INT_MAX - 1));
86 const double r = randomInteger(0, MAX);
87 return (r / MAX) * max;
88 }
89
90 bool CMathUtils::randomBool() { return randomInteger(0, 1); }
91
92 int CMathUtils::roundToMultipleOf(int value, int divisor)
93 {
94 Q_ASSERT(divisor != 0);
95 Q_ASSERT(divisor >= -std::numeric_limits<int>::max());
96 divisor = std::abs(divisor);
97 Q_ASSERT(std::abs(value) < std::numeric_limits<int>::max() - divisor / 2);
98
99 int multiplier = value / divisor;
100 int remainder = std::abs(value % divisor);
101 int shortfall = divisor - remainder;
102
103 if (shortfall < remainder)
104 {
105 multiplier += value < 0 ? -1 : 1;
106 }
107
108 return multiplier * divisor;
109 }
110
112 {
113 double intpart {};
114 const double fractpart = modf(value, &intpart);
115 const int prec = width >= 0 ? width + 1 : 10;
116 const QString f = QString::number(fractpart, 'f', prec); // avoid scientific notation
117 const QString fInt = f.length() < 3 ? QString("0") : f.mid(2);
118 if (width < 0)
119 {
120 return fInt;
121 }
122 if (fInt.length() >= width)
123 {
124 return fInt.left(width);
125 }
126 return fInt.leftJustified(width, '0');
127 }
128
129 double CMathUtils::sum(const QList<double> &values)
130 {
131 double sum = 0;
132 for (double v : values)
133 {
134 sum += v;
135 }
136 return sum;
137 }
138
139 QList<double> CMathUtils::squaredDifferences(const QList<double> &values)
140 {
141 const double meanValue = mean(values);
142 return squaredDifferences(values, meanValue);
143 }
144
145 QList<double> CMathUtils::squaredDifferences(const QList<double> &values, double meanValue)
146 {
147 QList<double> squaresDifferences;
148 for (double v : values)
149 {
150 const double vd = v - meanValue;
151 squaresDifferences.push_back(vd * vd);
152 }
153 return squaresDifferences;
154 }
155
156 double CMathUtils::mean(const QList<double> &values)
157 {
158 SWIFT_VERIFY_X(!values.isEmpty(), Q_FUNC_INFO, "Need values");
159 return sum(values) / values.size();
160 }
161
162 double CMathUtils::variance(const QList<double> &values)
163 {
164 const double variance = mean(squaredDifferences(values));
165 return variance;
166 }
167
169 {
170 const double sd = sqrt(variance(values));
171 return sd;
172 }
173
174 QPair<double, double> CMathUtils::standardDeviationAndMean(const QList<double> &values)
175 {
176 const double meanValue = mean(values);
177 const double varianceValue = mean(squaredDifferences(values, meanValue));
178 const double sd = sqrt(varianceValue);
179 return { sd, meanValue };
180 }
181} // namespace swift::misc::math
static double rad2deg(double radians)
Radians to degrees.
Definition mathutils.cpp:57
static double deg2rad(double degree)
Degrees to radians.
Definition mathutils.cpp:55
static bool epsilonEqual(float v1, float v2, float epsilon=1E-06f)
Epsilon safe equal.
Definition mathutils.cpp:51
static QRandomGenerator & randomGenerator()
Thread-local random generator.
Definition mathutils.cpp:71
static bool epsilonZeroLimits(double v)
Epsilon safe zero.
Definition mathutils.h:48
static int randomInteger(int low, int high)
Random number between low and high.
Definition mathutils.cpp:77
static bool randomBool()
Random boolean.
Definition mathutils.cpp:90
static double sum(const QList< double > &values)
Calculate the sum.
static int roundToMultipleOf(int value, int divisor)
Round numToRound to the nearest multiple of divisor.
Definition mathutils.cpp:92
static double normalizeDegrees180(double degrees)
Normalize: -180< degrees ≤180.
Definition mathutils.cpp:59
static QPair< double, double > standardDeviationAndMean(const QList< double > &values)
Standard deviation (first) and mean (second).
static double standardDeviation(const QList< double > &values)
Calculate the standard deviation.
static double mean(const QList< double > &values)
Calculate the mean.
static double round(double value, int digits)
Utility round method.
Definition mathutils.cpp:18
static QString fractionalPartAsString(double value, int width=-1)
Fractional part as integer string, e.g. 3.12 -> 12 / 3.012 -> 012.
static double normalizeDegrees360(double degrees)
Normalize: 0≤ degrees <360.
Definition mathutils.cpp:65
static double randomDouble(double max=1)
Random double 0-max.
Definition mathutils.cpp:83
static double roundEpsilon(double value, double epsilon)
Round by given epsilon.
Definition mathutils.cpp:33
constexpr double c_pi
PI.
Definition constants.h:14
bool isEmpty() const const
void push_back(QList< T >::parameter_type value)
qsizetype size() const const
double bounded(double highest)
QRandomGenerator * global()
QString left(qsizetype n) &&
QString leftJustified(qsizetype width, QChar fill, bool truncate) const const
qsizetype length() const const
QString mid(qsizetype position, qsizetype n) &&
QString number(double n, char format, int precision)
#define SWIFT_VERIFY_X(COND, WHERE, WHAT)
A weaker kind of assert.
Definition verify.h:26