Skip to content

Commit fba767b

Browse files
committed
Add randomGaussian() free function (Box-Muller transform)
1 parent eabc5e0 commit fba767b

1 file changed

Lines changed: 11 additions & 0 deletions

File tree

src/Processing.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1417,6 +1417,17 @@ inline bool toBoolean(const ::std::string& s) { return s=="true"||s=="1"
14171417
inline int toInt(const ::std::string& s) { return ::std::stoi(s); }
14181418
inline float toFloat(const ::std::string& s) { try { return ::std::stof(s); } catch (...) { return 0.0f; } }
14191419
inline char toChar(int v) { return static_cast<char>(v); }
1420+
// randomGaussian -- Box-Muller transform
1421+
inline float randomGaussian() {
1422+
static bool hasSpare = false;
1423+
static float spare;
1424+
if (hasSpare) { hasSpare = false; return spare; }
1425+
float u, v, s;
1426+
do { u = (rand()/(float)RAND_MAX)*2.f-1.f; v = (rand()/(float)RAND_MAX)*2.f-1.f; s=u*u+v*v; } while(s>=1.f||s==0.f);
1427+
float mul = ::std::sqrt(-2.f*::std::log(s)/s);
1428+
spare = v*mul; hasSpare = true;
1429+
return u*mul;
1430+
}
14201431
inline int parseInt(const ::std::string& s) { try { return ::std::stoi(s); } catch(...) { return 0; } }
14211432
inline float parseFloat(const ::std::string& s) { try { return ::std::stof(s); } catch(...) { return 0.f; } }
14221433
inline bool parseBoolean(const ::std::string& s){ return s=="true"||s=="True"||s=="TRUE"||s=="1"; }

0 commit comments

Comments
 (0)