get the 32th digit of pi in python

To get the 32nd digit of pi in python, you need to use the decimal module to set the appropriate precision, and then extract the digit. Here is one way to do it:

main.py
from decimal import *
getcontext().prec = 34  # set precision to 34 digits
pi = Decimal(22) / Decimal(7)  # calculate pi using the specified precision
digit = int(str(pi)[33])  # extract the 32nd digit (index 33 due to zero-based indexing)
print(digit)  # output: 4
266 chars
6 lines

In this code, we use getcontext().prec to set the precision of the decimal module to 34 digits. We then calculate pi using the Decimal(22) / Decimal(7) expression, which gives an approximation of pi with the specified precision. Finally, we extract the 32nd digit by converting the pi value to a string with str(pi), taking the character at index 33 (which corresponds to the 32nd digit), and converting it back to an integer with int(...).

gistlibby LogSnag