function calculatePi(iterations) {
let pi = 0;
let sign = 1;
for (let i = 0; i < iterations; i++) {
pi += sign / (2 * i + 1);
sign *= -1; // Alternate the sign
}
return pi * 4; // Multiply the result by 4
}
const iterations = 1000000000; // Number of iterations for the approximation
// Start measuring time
const start = Date.now();
const pi = calculatePi(iterations);
// Stop measuring time
const duration = Date.now() - start;
console.log(`Approximation of Pi after ${iterations} iterations: ${pi}`);
console.log(`Time taken: ${duration} ms`);
rust ->
use std::time::Instant;
fn main() {
let iterations = 1000000000; // Number of iterations for the approximation
let mut pi: f64 = 0.0;
let mut sign = 1.0;
// Start measuring time
let start = Instant::now();
for i in 0..iterations {
pi += sign / (2.0 * i as f64 + 1.0);
sign *= -1.0; // Alternate the sign
}
pi *= 4.0; // Multiply the result by 4
// Stop measuring time
let duration = start.elapsed();
println!("Approximation of Pi after {} iterations: {}", iterations, pi);
println!("Time taken: {:?}", duration);
}
js ->
rust ->