使用Rust计算圆周率
要使用 Rust 计算圆周率,可以使用蒙特卡罗方法。该方法通过在单位正方形中生成随机点,并计算落在单位圆内的点的数量来估计圆周率。
示例代码
运行这个程序需要添加rand
crate依赖;rand
是Rust的一个常用的随机数生成库,可用于生成伪随机序列;
use rand::Rng;
fn main() {
let total_points = 1000000;
let mut points_inside_circle = 0;
let mut rng = rand::thread_rng();
for _ in 0..total_points {
let x = rng.gen_range(-1.0..1.0);
let y = rng.gen_range(-1.0..1.0);
if x * x + y * y <= 1.0 {
points_inside_circle += 1;
}
}
let pi_estimate = 4.0 * (points_inside_circle as f64) / (total_points as f64);
println!("Estimated value of pi: {}", pi_estimate);
}