rustypi/
lib.rs

1use rand::Rng;
2
3/// A Monte Carlo simulation library for estimating the value of Pi.
4/// This is `rustypi`, a library that utilizes Monte Carlo methods to estimate numerical values.
5pub struct RustyPi {
6    samples: usize,
7}
8
9impl RustyPi {
10    /// Constructs a new `RustyPi`.
11    /// 
12    /// # Arguments
13    ///
14    /// * `samples` - The number of random points to generate for the simulation.
15    pub fn new(samples: usize) -> Self {
16        Self { samples }
17    }
18
19    /// Estimates the value of Pi using a Monte Carlo method.
20    pub fn estimate_pi(&self) -> f64 {
21        let mut inside_circle = 0;
22        let mut rng = rand::thread_rng();
23
24        for _ in 0..self.samples {
25            let x: f64 = rng.gen();
26            let y: f64 = rng.gen();
27            if x * x + y * y <= 1.0 {
28                inside_circle += 1;
29            }
30        }
31
32        4.0 * (inside_circle as f64) / (self.samples as f64)
33    }
34}