-
-
Save RandyMcMillan/02be268f1ea4938351dbe46c5ebcae58 to your computer and use it in GitHub Desktop.
pi_viete.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
fn calculate_pi_vieta(iterations: u32) -> f64 { | |
if iterations == 0 { | |
return 0.0; // Or handle as an error/special case | |
} | |
let mut current_sqrt_term = 0.0f64; // Represents the nested sqrt part (e.g., sqrt(2), sqrt(2+sqrt(2))) | |
let mut pi_approximation = 2.0f64; // Initialize with the leading '2' in the formula | |
for i in 0..iterations { | |
if i == 0 { | |
// First term: 2 / sqrt(2) | |
current_sqrt_term = 2.0f64.sqrt(); | |
} else { | |
// Subsequent terms: 2 / sqrt(2 + previous_sqrt_term) | |
current_sqrt_term = (2.0f64 + current_sqrt_term).sqrt(); | |
} | |
// Multiply the approximation by 2 / current_sqrt_term | |
pi_approximation *= 2.0 / current_sqrt_term; | |
} | |
pi_approximation | |
} | |
fn main() { | |
println!("std::f64::consts::PI\n{:.11}", std::f64::consts::PI); | |
let iterations = 17; // Number of terms to calculate for the approximation | |
let pi_approx = calculate_pi_vieta(iterations); | |
println!( | |
"Viète's formula with {} iterations:\n{:.11}", | |
iterations, pi_approx | |
); | |
let iterations_high = 18; | |
let pi_approx_high = calculate_pi_vieta(iterations_high); | |
println!( | |
"Viète's formula with {} iterations:\n{:.11}", | |
iterations_high, pi_approx_high | |
); | |
let iterations_very_high = 19; // Beyond this, f64 precision limits might show | |
let pi_approx_very_high = calculate_pi_vieta(iterations_very_high); | |
println!( | |
"Viète's formula with {} iterations:\n{:.11}", | |
iterations_very_high, pi_approx_very_high | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment