chatgpt-4o-latest-20250326· OpenAI
LMArena Human Preference 140K
Write me a typescript function for computing pi
- User
Write me a typescript function for computing pi
- Assistant
Sure! Here's a simple TypeScript function to compute an approximation of π (pi) using the Leibniz formula for π:
🔢 Leibniz Formula for π
The formula is:
[ \pi = 4 \left(1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \cdots \right) ]
This is an infinite series, so we compute a number of terms to approximate π.
✅ TypeScript Function
function computePi(iterations: number): number { let pi = 0; let denominator = 1; let sign = 1; for (let i = 0; i < iterations; i++) { pi += sign * (4 / denominator); denominator += 2; sign *= -1; // alternate between positive and negative } return pi; }
📌 Example Usage
const approximatedPi = computePi(1_000_000); console.log("Approximated π:", approximatedPi); console.log("Math.PI:", Math.PI);
💬 Notes
- The more iterations you use, the closer the result will be to the real value of π.
- The Leibniz series converges very slowly, so for high precision you'd need millions of iterations.
Interested in a faster-converging method like the Nilakantha series, or want to benchmark performance? Let me know!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.