Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Last active February 9, 2026 02:57
Show Gist options
  • Select an option

  • Save RandyMcMillan/3f2e12f4e118f5b479cb5cd4f64149b3 to your computer and use it in GitHub Desktop.

Select an option

Save RandyMcMillan/3f2e12f4e118f5b479cb5cd4f64149b3 to your computer and use it in GitHub Desktop.
bayes_theorum.rs
struct Probability {
value: f64,
}
impl Probability {
fn new(p: f64) -> Self {
assert!(
(0.0..=1.0).contains(&p),
"Probability must be between 0 and 1"
);
Self { value: p }
}
}
/// Calculates P(A|B) using Bayes' Theorem: P(A|B) = (P(B|A) * P(A)) / P(B)
fn bayes_theorem(p_b_given_a: f64, p_a: f64, p_b: f64) -> f64 {
(p_b_given_a * p_a) / p_b
}
fn main() {
let p_a = 0.10; // Prior: Probability of having a rare disease
let p_b_given_a = 0.99; // Likelihood: Test is 99% accurate for positive cases
let p_b = 0.05; // Evidence: Total probability of testing positive
let result = bayes_theorem(p_b_given_a, p_a, p_b);
println!("The probability of A given B is: {:.2}%", result * 100.0);
}
@RandyMcMillan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment