Daily Perf Improver: Optimize Marsaglia Gaussian generator with sample caching #50
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR implements a performance optimization for the Marsaglia Gaussian generator in the
Random.Normal()method by caching the second sample generated during each polar method execution, providing approximately 2x improvement in random number generation efficiency.Performance Improvement Goal
From the Daily Performance Improver Research & Plan, this addresses Round 1: Low-Hanging Fruit - specifically fixing the Marsaglia Gaussian generator to cache the second sample for a 2x improvement.
Changes Made
cachedNormalandhasCachedNormaltoRandomclassRandom.Seed()is called to preserve reproducible behaviorTechnical Details
Before (Original Implementation)
After (Optimized Implementation)
Performance Measurements
Normal()sample (measured on 1M samples)NextDouble()calls for normal distribution samplingCorrectness Verification
Statistical properties are preserved across 100,000 sample tests:
Test Plan
Future Work
This optimization enables further performance improvements:
Commands Used
This implementation directly addresses the TODO comment in the original code and provides measurable performance improvements while maintaining mathematical correctness and API compatibility.