From 00794ec95681a525c11e62e72ae98486ec262627 Mon Sep 17 00:00:00 2001 From: Yi Zhang Date: Sun, 22 Sep 2024 12:11:17 +0800 Subject: [PATCH] add complex random --- lib/maths/mathfunc.cpp | 15 +++++++++++++++ lib/maths/mathfunc.h | 17 +++++++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/lib/maths/mathfunc.cpp b/lib/maths/mathfunc.cpp index 7da843a..45a1990 100644 --- a/lib/maths/mathfunc.cpp +++ b/lib/maths/mathfunc.cpp @@ -38,6 +38,21 @@ double gctl::random(double low, double hig) return f*(hig-low) + low; } +std::complex random(std::complex low, std::complex hig) +{ + std::complex c; + double r = (double) rand()/RAND_MAX; + double i = (double) rand()/RAND_MAX; + double rh = std::max(hig.real(), low.real()); + double rl = std::min(hig.real(), low.real()); + double ih = std::max(hig.imag(), low.imag()); + double il = std::min(hig.imag(), low.imag()); + + c.real(r*(rh - rl) + rl); + c.imag(i*(ih - il) + il); + return c; +} + bool gctl::isequal(double f, double v, double eps) { return fabs(f - v) < eps; diff --git a/lib/maths/mathfunc.h b/lib/maths/mathfunc.h index d5976b4..702e4d4 100644 --- a/lib/maths/mathfunc.h +++ b/lib/maths/mathfunc.h @@ -45,10 +45,9 @@ namespace gctl * * @note Call srand(seed) to initiate the random squence before using this function. * - * @tparam T Value type * @param low Lower bound * @param hig Higher bound - * @return T Random value + * @return Random value */ int random(int low, int hig); @@ -57,13 +56,23 @@ namespace gctl * * @note Call srand(seed) to initiate the random squence before using this function. * - * @tparam T Value type * @param low Lower bound * @param hig Higher bound - * @return T Random value + * @return Random value */ double random(double low, double hig); + /** + * @brief Return a random number in the range [low, hig] + * + * @note Call srand(seed) to initiate the random squence before using this function. + * + * @param low Lower bound + * @param hig Higher bound + * @return Random value + */ + std::complex random(std::complex low, std::complex hig); + /** * @brief 比较两个浮点数。注意比较的精度为 eps 减一位,比如 eps 为1e-10则比较的精度为小数点后9位。 *