Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 20, 2025 13:06
Show Gist options
  • Select an option

  • Save rust-play/19361ba3cb0cbdb211a2a766e8ad1cbc to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/19361ba3cb0cbdb211a2a766e8ad1cbc to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::f64::consts::PI;
/// Calculates an approximation of Pi using Viète's formula.
///
/// The formula is based on an infinite product of terms involving nested square roots.
/// This function approximates the product up to a given number of iterations.
///
/// # Arguments
///
/// * `iterations` - The number of terms to include in the product. More iterations
/// lead to a more precise approximation.
///
/// # Returns
///
/// The calculated approximation of Pi as a `f64`.
fn viete_pi_approximation(iterations: u32) -> f64 {
let mut product = 1.0;
let mut current_sqrt_term = 0.0;
for _ in 0..iterations {
// Recursively calculate the next nested square root term.
// For the first iteration, this is sqrt(2 + 0) = sqrt(2).
// For subsequent iterations, it's sqrt(2 + previous_term).
current_sqrt_term = (2.0f64 + current_sqrt_term).sqrt();
// Multiply the next factor into the running product.
// The factor is 2 divided by the current nested square root term.
product *= 2.0 / current_sqrt_term;
}
// According to the formula, Pi is 2 times the infinite product.
2.0 * product
}
fn main() {
let iterations = u32::MAX/(u32::MAX/999999999u32);
let pi_approx = viete_pi_approximation(iterations);
println!("Calculating Pi with Viète's formula:");
println!("Number of iterations: {}", iterations);
println!("Approximation of Pi: {}", pi_approx);
println!("Actual Pi (from `std::f64::consts::PI`): {}", PI);
println!("Difference: {}", (PI - pi_approx).abs());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment