-
-
Save RandyMcMillan/1562909740d258b6d306eef9c3107cb6 to your computer and use it in GitHub Desktop.
guassian_pi_approx.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use approx::assert_relative_eq; | |
| fn gaussian_integral_approximation(start: f64, end: f64, steps: usize) -> f64 { | |
| let dx = (end - start) / steps as f64; | |
| let f = |x: f64| (-x.powi(2)).exp(); | |
| let mut sum = (f(start) + f(end)) * 0.5; | |
| for i in 1..steps { | |
| let x = start + (i as f64 * dx); | |
| sum += f(x); | |
| } | |
| sum * dx | |
| } | |
| fn main() { | |
| let bounds = 10.0; | |
| let val = gaussian_integral_approximation(-bounds, bounds, 1_000_000); | |
| println!("Value: {}", val); | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::*; | |
| use std::f64::consts::PI; | |
| #[test] | |
| fn test_gaussian_full_range() { | |
| let theoretical = PI.sqrt(); | |
| // Integration from -10 to 10 is sufficient for f64 precision | |
| let estimated = gaussian_integral_approximation(-10.0, 10.0, 1_000_000); | |
| assert_relative_eq!(theoretical, estimated, epsilon = 1e-10); | |
| } | |
| #[test] | |
| fn test_symmetry_half_integral() { | |
| let theoretical = PI.sqrt() / 2.0; | |
| // The Gaussian curve is symmetric; the integral from 0 to infinity is half | |
| let estimated = gaussian_integral_approximation(0.0, 10.0, 500_000); | |
| assert_relative_eq!(theoretical, estimated, epsilon = 1e-10); | |
| } | |
| #[test] | |
| #[ignore] | |
| fn test_convergence_improvement() { | |
| let theoretical = PI.sqrt(); | |
| let coarse = gaussian_integral_approximation(-10.0, 10.0, 100); | |
| let fine = gaussian_integral_approximation(-10.0, 10.0, 10_000); | |
| let error_coarse = (theoretical - coarse).abs(); | |
| let error_fine = (theoretical - fine).abs(); | |
| // Higher step count should result in a smaller error | |
| assert!(error_fine < error_coarse); | |
| } | |
| #[test] | |
| fn test_zero_width_interval() { | |
| // Integrating from 'a' to 'a' should always be zero | |
| let result = gaussian_integral_approximation(5.0, 5.0, 100); | |
| assert_eq!(result, 0.0); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=883e05211d6e1560bcfbde7fc85740bb