Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there number limitations in python?

Tags:

python

pi

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
like image 556
Joe Allen Avatar asked Jan 09 '17 17:01

Joe Allen


People also ask

Does Python have a number limit?

Unlike C/C++ Long in Python 3 have unlimited precision and there is no explicitly defined limit.

How many numbers can Python handle?

The pythonic way Similarly for python, "digit" is in base 2³⁰ which means it will range from 0 to 2³⁰ - 1 = 1073741823 of the decimal system.

What is the highest number Python can handle?

Integers are unlimited in size and have no maximum value in Python.


1 Answers

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.

like image 149
jmd_dk Avatar answered Oct 27 '22 03:10

jmd_dk