Skip to content

Commit

Permalink
Added fast_random_gaussian()
Browse files Browse the repository at this point in the history
  • Loading branch information
baranovmv committed Apr 28, 2024
1 parent 7c3b835 commit c1af1f1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/internal_modules/roc_core/fast_random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,20 @@ uint32_t fast_random_range(uint32_t from, uint32_t to) {
return ret;
}

// Gaussian PRNG implementation is based on Box-Muller transform:
// https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
double fast_random_gaussian() {
// Generate two uniform random numbers
double u1 = (double)roc::core::fast_random() / (double)UINT32_MAX;
double u2 = (double)roc::core::fast_random() / (double)UINT32_MAX;

// Use Box-Muller transform to convert uniform random numbers to normal random numbers
double r = std::sqrt(-2.0 * std::log(u1));
double theta = 2.0 * M_PI * u2;

// Return one of the normal random numbers
return r * std::cos(theta);
}

} // namespace core
} // namespace roc
5 changes: 5 additions & 0 deletions src/internal_modules/roc_core/fast_random.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ uint32_t fast_random();
//! @returns random value in inclusive range [from; to].
uint32_t fast_random_range(uint32_t from, uint32_t to);

//! Get a random double from a non cryptographically secure, but fast PRNG.
//! Thread-safe.
//! @returns normally distibure random value with 1 variance.
double fast_random_gaussian();

} // namespace core
} // namespace roc

Expand Down

0 comments on commit c1af1f1

Please sign in to comment.