Rust

PI - Monte Carlo (Parallelism)


參考資訊:
1. rust-concurrency
2. go-concurrency-is-not-parallelism-real-world-lessons-with-monte-carlo-simulations

產生樣板

$ cargo new hello
$ cd hello

Cargo.toml

[package]
name = "hello"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8"

src/main.rs

use rand::Rng;
use std::thread;

fn _pi(samples : u32) -> f64 {
    let mut inside : u32 = 0;
    let mut rng = rand::thread_rng();

    for _ in 0..samples {
        let x : f64 = (rng.gen::<u32>() as f64) / f64::from(u32::MAX);
        let y : f64 = (rng.gen::<u32>() as f64) / f64::from(u32::MAX);

        if ((x * x) + (y * y)) < 1.0 {
            inside = inside + 1;
        }
    }

    if inside > 0 {
        return (f64::from(inside) / f64::from(samples)) * 4.0;
    }
    return 0.0;
}

fn main() {
    let mut handles = Vec::new();

    for i in 2..=8 {
        let s = u32::pow(10, i);
        let handle = thread::spawn(move || {
            println!("Our value of Pi after {} runs: {}", s, _pi(s));
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
}

執行

$ cargo run
    Our value of Pi after 1000 runs: 3.136
    Our value of Pi after 100 runs: 2.88
    Our value of Pi after 10000 runs: 3.1136
    Our value of Pi after 100000 runs: 3.14588
    Our value of Pi after 1000000 runs: 3.142252
    Our value of Pi after 10000000 runs: 3.1424932
    Our value of Pi after 100000000 runs: 3.1419658


返回上一頁