Monte Carlo Pattern
Tutorial Video
Text description (accessibility)
This video demonstrates the "Monte Carlo Pattern" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. Some problems are too complex for exact algorithms but can be approximated by random sampling. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Some problems are too complex for exact algorithms but can be approximated by random sampling. Monte Carlo methods estimate quantities by sampling: estimate pi by generating random points in a unit square and counting those inside the unit circle; estimate integrals by averaging function values at random points; approximate Nash equilibria in game theory; simulate financial option pricing. Error decreases as O(1/sqrt(n)) — independent of dimensionality, which is the key advantage over deterministic quadrature for high-dimensional integration. Monte Carlo underpins financial risk models, particle physics simulation, and probabilistic algorithms.
🎯 Learning Outcomes
integral(f, a, b) by averaging f at random pointsCode Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| RNG | rand::RngCore trait | Random module (LCG-based) |
| Testability | Seeded SmallRng::seed_from_u64 | Random.init seed |
| Parallelism | rayon::par_iter() | Domain.spawn (OCaml 5.0) |
| Sample counting | filter().count() | Mutable counter in loop |
| Convergence | O(1/sqrt n) | Same |
| Higher dimensions | Same complexity advantage | Same |
OCaml Approach
OCaml's Monte Carlo uses Random.float 2.0 -. 1.0 for uniform samples. The pi estimation is: let count = ref 0 in for _ = 1 to n do let x = ... and y = ... in if x*.x +. y*.y <= 1.0 then incr count done; 4.0 *. float !count /. float n. OCaml's Random.self_init () seeds from system entropy. The Seq module creates an infinite sample sequence for lazy Monte Carlo. OCaml's Float.sqrt and .*. operators handle the computation.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Monte Carlo Pattern
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
x1^2 + ... + x10^2 <= 1 to demonstrate the dimensionality advantage.