Sound Byte Libs 0.5.1-121-g3358a44
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
rng.hpp
Go to the documentation of this file.
1// sbl/dsp/rng.hpp — Lightweight pseudorandom number generator
2//
3// xorshift32 PRNG for audio/control applications. Not cryptographic.
4// Period: 2^32-1. Each instance maintains independent state.
5//
6// Use cases: analog drift, sample-and-hold, stochastic gates,
7// randomized delay taps, noise modulation at control rate.
8//
9// Usage:
10// sbl::dsp::Rng rng(42); // seed at construction
11// float r = rng.bipolar(); // [-1.0, 1.0]
12// float u = rng.unipolar(); // [0.0, 1.0]
13// uint32_t raw = rng.next(); // raw 32-bit
14
15#ifndef SBL_DSP_PRIMITIVES_RNG_HPP_
16#define SBL_DSP_PRIMITIVES_RNG_HPP_
17
18#include <cstdint>
19
20namespace sbl::dsp::primitives {
21
22class Rng {
23public:
24 /// @note All public methods are ISR-safe — bounded computation, no I/O.
25
26 /// Construct with seed. Each instance should use a different seed
27 /// to ensure uncorrelated output.
28 explicit Rng(uint32_t seed = 1) : state_(seed ? seed : 1) {}
29
30 /// Advance state and return raw 32-bit value.
31 uint32_t next() {
32 state_ ^= state_ << 13;
33 state_ ^= state_ >> 17;
34 state_ ^= state_ << 5;
35 return state_;
36 }
37
38 /// Random float in [-1.0, 1.0].
39 float bipolar() {
40 // Shift right 1 to get [0, 2^31-1], scale to [0, 1], then to [-1, 1]
41 return (static_cast<float>(next() >> 1) / 1073741824.0f) - 1.0f;
42 }
43
44 /// Random float in [0.0, 1.0].
45 float unipolar() {
46 return static_cast<float>(next() >> 1) / 2147483647.0f;
47 }
48
49 /// Set state directly (for test reproducibility).
50 void seed(uint32_t s) { state_ = s ? s : 1; }
51
52private:
53 uint32_t state_;
54};
55
56} // namespace sbl::dsp::primitives
57
58#endif // SBL_DSP_PRIMITIVES_RNG_HPP_
float unipolar()
Random float in [0.0, 1.0].
Definition rng.hpp:45
float bipolar()
Random float in [-1.0, 1.0].
Definition rng.hpp:39
Rng(uint32_t seed=1)
Definition rng.hpp:28
uint32_t next()
Advance state and return raw 32-bit value.
Definition rng.hpp:31
void seed(uint32_t s)
Set state directly (for test reproducibility).
Definition rng.hpp:50
Stateful, single-concern building blocks.