ExamplesBy LevelBy TopicLearning Paths
846 Fundamental

Monte Carlo Pattern

Functional Programming

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

  • • Implement pi estimation: sample (x,y) uniformly in [-1,1]^2, count points where x^2+y^2 < 1
  • • Understand O(1/sqrt(n)) convergence: 4x more samples gives 2x more accuracy
  • • Implement Monte Carlo integration: estimate integral(f, a, b) by averaging f at random points
  • • Apply to high-dimensional integration where deterministic methods are exponentially expensive
  • • Recognize the importance of a good random number generator (LCG vs PCG vs Mersenne Twister)
  • Code Example

    #![allow(clippy::all)]
    //! Placeholder

    Key Differences

    AspectRustOCaml
    RNGrand::RngCore traitRandom module (LCG-based)
    TestabilitySeeded SmallRng::seed_from_u64Random.init seed
    Parallelismrayon::par_iter()Domain.spawn (OCaml 5.0)
    Sample countingfilter().count()Mutable counter in loop
    ConvergenceO(1/sqrt n)Same
    Higher dimensionsSame complexity advantageSame

    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)]
    //! Placeholder

    Deep Comparison

    OCaml vs Rust: Monte Carlo Pattern

    Overview

    See the example.rs and example.ml files for detailed implementations.

    Key Differences

    AspectOCamlRust
    Type systemHindley-MilnerOwnership + traits
    MemoryGCZero-cost abstractions
    MutabilityExplicit refmut keyword
    Error handlingOption/ResultResult<T, E>

    See README.md for detailed comparison.

    Exercises

  • Implement Monte Carlo integration for a 1D function and compare with the exact analytical result.
  • Extend to 10D integration of x1^2 + ... + x10^2 <= 1 to demonstrate the dimensionality advantage.
  • Use stratified sampling (divide the domain into strata, sample uniformly within each) and compare convergence with naive Monte Carlo.
  • Implement parallel Monte Carlo using Rayon with independent per-thread RNGs and measure linear speedup.
  • Estimate the variance of your pi estimator as a function of n and verify it matches the theoretical O(1/n) variance.
  • Open Source Repos