A Python program that computes π (pi) one digit at a time and outputs each digit as it's computed.
This project implements two different algorithms to calculate the digits of π one at a time:
- Spigot Algorithm (pi_calculator.py): An unbounded spigot algorithm that generates digits of π sequentially
- Nilakantha Series (pi_calculator_bbp.py): A simplified implementation that demonstrates the concept of generating π digits one at a time
Both implementations:
- Compute π digit by digit
- Display each digit as it's calculated
- Format the output for readability
- Can be interrupted at any time with Ctrl+C
- Python 3.6 or higher
Run either implementation with:
# Spigot Algorithm (more accurate)
python pi_calculator.py
# Nilakantha Series (simplified demonstration)
python pi_calculator_bbp.pyBy default, the Spigot implementation will compute 1000 digits, while the Nilakantha implementation will compute 100 digits. You can modify these by changing the num_digits variable in the respective main() functions.
The Spigot algorithm is an unbounded algorithm that can generate an arbitrary number of digits of π. It works by:
- Maintaining a set of state variables
- Performing transformations on these variables
- Extracting one digit of π with each iteration
The algorithm is memory-efficient and doesn't require storing all previously computed digits.
The implementation in pi_calculator_bbp.py uses a combination of:
- Pre-computed digits for the first few decimal places
- A simple pattern generator for additional digits (for demonstration purposes)
In a real-world application, you would use a more sophisticated algorithm like the Bailey-Borwein-Plouffe (BBP) formula or continue the Nilakantha series with higher precision.
Computing π one digit at a time:
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679...
This project is open source and available under the MIT License.