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
Unlike C/C++ Long in Python 3 have unlimited precision and there is no explicitly defined limit.
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.
Integers are unlimited in size and have no maximum value in Python.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With