Search code examples
pythonpi

Are there number limitations in python?


I have made a Python 3 program to calculate pi for a school project, but it always stops at 16 decimal places. Is there a limit to the length of numbers in python? If so is there a language that I could use that will let me continue?

accuracy = int(input("accuracy:  "))

current = 2
opperation = "+"
number = 3
count = 1

for i in range (accuracy):
    if opperation == "-":
        number = number - (4/(current*(current+1)*(current+2)))
        opperation = "+"
    elif opperation == "+":
        number = number + (4/(current*(current+1)*(current+2)))
        opperation = "-"
    current += 2
    print(str(count).zfill(8)) + ":    " + str(number)
    count += 1

Solution

  • There is no restriction if you are working with integers and Python 3.x. The precision you get using floating point numbers is however limited. A Python float (like 3.14) is really a C double, which have about 16 decimals of precision, as you say.

    You can use the decimal module to create and work with other floating point numbers with arbitrary precision. Example code:

    # Normal Python floats
    a = 0.000000000000000000001
    b = 1 + 2*a
    print(b)  # Prints 1.0
    
    # Using Decimal
    import decimal
    decimal.getcontext().prec = 100  # Set the precision
    a = decimal.Decimal('0.000000000000000000001')
    b = 1 + 2*a
    print(b)  # Prints 1.000000000000000000002
    

    See the docs for more information on decimal.