python有人数限制吗?
Are there number limitations in python?
我制作了一个 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,则没有限制。但是,使用浮点数获得的精度是有限的。 Python float
(如 3.14
)实际上是一个 C double
,如您所说,它具有大约 16 位小数的精度。
您可以使用 decimal
模块创建和使用任意精度的其他浮点数。示例代码:
# 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
有关 decimal
的更多信息,请参阅 the docs。
我制作了一个 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,则没有限制。但是,使用浮点数获得的精度是有限的。 Python float
(如 3.14
)实际上是一个 C double
,如您所说,它具有大约 16 位小数的精度。
您可以使用 decimal
模块创建和使用任意精度的其他浮点数。示例代码:
# 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
有关 decimal
的更多信息,请参阅 the docs。