我制作了一个 Python 3 程序来计算学校项目的圆周率,但它总是停在小数点后 16 位。 python中数字的长度有限制吗?如果是这样,是否有一种我可以使用的语言可以让我继续?
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
最佳答案
如果您使用整数和 Python 3.x,则没有限制。但是,使用 float 获得的精度是有限的。 Python float
(如 3.14
)实际上是 C double
,正如您所说,它具有大约 16 位小数的精度。
您可以使用 decimal
模块来创建和使用任意精度的其他 float 。示例代码:
# 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
参见 the docs有关 decimal
的更多信息。
关于python - python有数量限制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41553774/