Are there number limitations in python?

筅森魡賤 提交于 2021-01-27 01:41:07

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/41553774/are-there-number-limitations-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!