Alright, one of the most famous numbers in math pi! You know, that ***** little guy with all those decimal places that goes on forever? Well, today we’re going to learn how to compute some digits of it using a computer.
To set the stage, what is pi exactly? It’s an irrational number (meaning it can’t be expressed as a fraction) and represents the ratio between the circumference and diameter of any circle. So basically, if you have a circular object with a diameter of 10 inches, its circumference would be approximately 31.4 inches that’s pi!
Now let’s get to the fun part: computing digits using Python. We’re going to use the decimal module in Python which allows us to work with arbitrary precision numbers (meaning we can have as many decimal places as our computer can handle).
Here’s a simple script that computes pi up to 10 decimal places:
# Import the decimal module to work with arbitrary precision numbers
from decimal import *
# Set the number of digits for precision to 38
getcontext().prec = 38
# Create a Decimal object with the value of 3
three = Decimal(3)
# Initialize variables for the loop
lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
# Loop until convergence is reached
while True:
# Store the current value of s in lasts for comparison
lasts = s
# Update the values of n and na
n, na = n+na, na+8
# Update the values of d and da
d, da = d+da, da+32
# Calculate the next term in the series and add it to s
t = (t * n) / d
s += t
# Check for convergence by comparing the absolute value of s and lasts
if abs(s - lasts) < 1e-15:
break
# Print the value of pi up to 10 decimal places
print("Pi up to 10 decimal places:", round(s, 10))
Let’s go through this line by line. First we import the decimal module and set our precision to 38 (which is more than enough for 10 decimal places). Then we initialize some variables: three represents the value of 3 as a Decimal object, lasts keeps track of the previous sum, t is an intermediate variable used in the calculation, s is the current sum, n and na are used to calculate the next term in the series, d and da are used for calculating the denominator.
The while loop runs until convergence (meaning we’ve reached a certain level of accuracy). We check this by comparing the absolute difference between the last sum and the new sum with 1e-15 this is because floating point numbers can have some inaccuracies due to their representation, so we need to set a threshold for when it’s close enough.
Finally, we print out our result rounded to 10 decimal places using Python’s built-in round() function. We now know the value of pi up to 10 decimal places: 3.141592653589793.
Of course, you can adjust this script to compute more or fewer digits by changing the precision and/or the threshold for convergence.