mirror of
https://github.com/swift-project/pilotclient.git
synced 2026-04-06 01:45:38 +08:00
Ref T486 Using QRandomGenerator.
This commit is contained in:
@@ -99,32 +99,30 @@ namespace BlackMisc
|
||||
return (result >= 0.0) ? result : result + 360.0;
|
||||
}
|
||||
|
||||
QRandomGenerator &CMathUtils::randomGenerator()
|
||||
{
|
||||
thread_local QRandomGenerator rng(QRandomGenerator::global()->generate());
|
||||
return rng;
|
||||
}
|
||||
|
||||
int CMathUtils::randomInteger(int low, int high)
|
||||
{
|
||||
static QThreadStorage<uint> seeds;
|
||||
Q_ASSERT_X(high < INT_MAX, Q_FUNC_INFO, "Cannot add 1");
|
||||
Q_ASSERT_X(low >= 0 && high >= 0, Q_FUNC_INFO, "Only valid for positive values");
|
||||
if (!seeds.hasLocalData())
|
||||
{
|
||||
// seed is per thread!
|
||||
const uint seed = static_cast<uint>(QTime::currentTime().msec());
|
||||
qsrand(seed);
|
||||
seeds.setLocalData(seed);
|
||||
}
|
||||
const int r(qrand());
|
||||
const int mod = (high + 1) - low;
|
||||
Q_ASSERT_X(mod <= RAND_MAX, Q_FUNC_INFO, "RAND_MAX exceeded");
|
||||
return (r % mod) + low;
|
||||
return randomGenerator().bounded(low, high + 1);
|
||||
}
|
||||
|
||||
double CMathUtils::randomDouble(double max)
|
||||
{
|
||||
// on Win system, RAND_MAX is only 16bit, on other systems higher
|
||||
static const int MAX(RAND_MAX < INT_MAX ? RAND_MAX - 1 : INT_MAX - 1);
|
||||
constexpr int MAX(std::min(RAND_MAX - 1, INT_MAX - 1));
|
||||
const double r = randomInteger(0, MAX);
|
||||
return (r / MAX) * max;
|
||||
}
|
||||
|
||||
bool CMathUtils::randomBool()
|
||||
{
|
||||
return randomInteger(0, 1);
|
||||
}
|
||||
|
||||
int CMathUtils::roundToMultipleOf(int value, int divisor)
|
||||
{
|
||||
Q_ASSERT(divisor != 0);
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
#include "blackmisc/blackmiscexport.h"
|
||||
|
||||
#include <QRandomGenerator>
|
||||
#include <QtCore/qmath.h>
|
||||
#include <QPair>
|
||||
#include <cmath>
|
||||
@@ -115,12 +116,18 @@ namespace BlackMisc
|
||||
//! Normalize: 0≤ degrees <360
|
||||
static double normalizeDegrees360(double degrees);
|
||||
|
||||
//! Thread-local random generator
|
||||
static QRandomGenerator &randomGenerator();
|
||||
|
||||
//! Random number between low and high
|
||||
static int randomInteger(int low, int high);
|
||||
|
||||
//! Random double 0-max
|
||||
static double randomDouble(double max = 1);
|
||||
|
||||
//! Random boolean
|
||||
static bool randomBool();
|
||||
|
||||
//! Round numToRound to the nearest multiple of divisor
|
||||
static int roundToMultipleOf(int value, int divisor);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user