eis/eqpalg/.do_not_use/utility-no-use/RandT.h

54 lines
1.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#pragma once
/**
* @file RandT.h
* @brief 随机数
* @author your name (you@domain.com)
* @version 0.1
* @date 2023-12-22
*
* Copyright: Baosight Co. Ltd.
* DO NOT COPY/USE WITHOUT PERMISSION
*
*/
#include <time.h>
#include <cmath>
namespace RandT {
/**
* @brief 生成指定范围内的随机数
* @tparam T
* @param _min min
* @param _max max
* @return T
*/
template <typename T>
T RandT(T _min, T _max) {
T temp;
if (_min > _max) {
temp = _max;
_max = _min;
_min = temp;
}
return rand() / (double)RAND_MAX * (_max - _min) + _min;
}
/**
* @brief 生成高斯分布的随机数
* @param mean 均值
* @param sigma 标准差
* @return double
*/
double GuassRand(double mean = 0, double sigma = 0) {
double U1 = rand() * 1.0f / RAND_MAX; // 0~1均匀分布
double U2 = rand() * 1.0f / RAND_MAX; // 0~1均匀分布
double Z =
sqrt(-2 * log(U1)) * cos(2 * M_PI * U2); // 均值为0方差为1的正态分布
double Y;
if (sigma >= 0) {
Y = mean + sqrt(sigma) * Z;
} else {
Y = mean + Z;
}
return Y;
}
} // namespace RandT