ProbabilityTheory/src/bin/lab-2.rs

54 lines
1.6 KiB
Rust
Raw Normal View History

2024-03-09 18:24:47 +02:00
use rand::random;
const SAMPLE_SIZE: usize = 5_000;
fn simpson_from_uniform(m: i32, a: i32, r: f32) -> f32 {
if r <= 0.5 {
let d = (2f32 * r).sqrt() / 0.2;
(m - a) as f32 + d
} else {
let d = (2f32 * (1f32 - r)).sqrt() / 0.2;
(m + a) as f32 - d
}
}
fn mean(distribution: &[f32]) -> f32 {
distribution.iter().sum::<f32>() / distribution.len() as f32
}
fn dispersion(mean: f32, distribution: &[f32]) -> f32 {
distribution
.iter()
.map(|x| (*x - mean).powi(2))
.sum::<f32>()
/ distribution.len() as f32
}
fn standard_deviation(mean: f32, distribution: &[f32]) -> f32 {
dispersion(mean, distribution).sqrt()
}
fn probability_in_limits(lower: f32, upper: f32, distribution: &[f32]) -> f32 {
distribution
.iter()
.filter(|x| **x > lower && **x < upper)
.count() as f32
/ distribution.len() as f32
}
fn main() {
let set_m = 20;
let set_a = 5;
let simpson_numbers: Vec<f32> = (0..=SAMPLE_SIZE)
.map(|_| simpson_from_uniform(set_m, set_a, random::<f32>()))
.collect();
let m = mean(&simpson_numbers);
let std_dev = standard_deviation(m, &simpson_numbers);
let probability = probability_in_limits(17f32, 24f32, &simpson_numbers);
println!("Математичне очікування розподілу: {m}");
println!("Середньоквадратичне відхилення розподілу: {std_dev}");
println!("Ймовірність потрапляння у проміжок [17; 24]: {probability}");
}