我做了一个Python3程序来计算学校项目的pi,但它总是停在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发布于 2017-01-10 01:51:47
如果您使用的是整数和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。
https://stackoverflow.com/questions/41553774
复制相似问题