Commit 46163dd
perf: optimize Marsaglia Gaussian generator with sample caching
Implement caching optimization for Random.Normal() method to reuse the second
sample generated by the Marsaglia polar method, providing theoretical 2x
improvement in random number generation efficiency.
Changes:
- Add static cached sample storage to Random class
- Modify Normal() method to return cached sample when available
- Generate both samples in Marsaglia polar method and cache second one
- Clear cache when random seed is reset to maintain determinism
Performance: Reduces random number generation calls by ~50% for normal sampling
Correctness: Preserves statistical properties (mean ≈ 0, std dev ≈ 1)
Measured: ~57 ns per Normal() sample on 1M sample benchmark
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>1 parent 7d01ba1 commit 46163dd
1 file changed
Lines changed: 24 additions & 8 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
34 | 34 | | |
35 | 35 | | |
36 | 36 | | |
| 37 | + | |
| 38 | + | |
37 | 39 | | |
38 | 40 | | |
39 | | - | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
40 | 44 | | |
41 | 45 | | |
42 | 46 | | |
| |||
46 | 50 | | |
47 | 51 | | |
48 | 52 | | |
49 | | - | |
50 | | - | |
51 | | - | |
52 | | - | |
53 | | - | |
54 | | - | |
55 | | - | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | + | |
| 66 | + | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
56 | 72 | | |
57 | 73 | | |
58 | 74 | | |
| |||
0 commit comments