Search code examples
pythondigitspi

PI nth digit after decimal


I want to make a program which will return a nth number of digits after decimal in PI number. It works good as long as I don't put n higher than 50. Can I fix it or Python don't allow that?

Here's my code:

pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428


def nth_pi_digit(n=input("How many digits after decimal you would like to see?(PI number):  ")):
    try:
        n = int(n)
        if n <= 204:
            return print(format(pi, f".{n}f"))
        else:
            print("Sorry, we have pi with 204 digits after decimal, so we'll print that")
            return print(format(pi, ".204f"))
    except:
        print("You need to put a integer digit")


nth_pi_digit()

Solution

  • The float datatype has a limit on how precise you can get. 50 digits is around that.

    I recommend using a Decimal instead to represent numbers with such high precision:

    >>> from decimal import Decimal
    >>> d = Decimal('3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428')
    >>> format(d, ".50f")
    '3.14159265358979323846264338327950288419716939937511'
    >>> format(d, ".204f")
    '3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102709385211055596446229489549303819644280'
    

    This way you can do math on it without losing precision, which "treating it as a string" doesn't let you do.