python - python有数量限制吗?

标签 python pi

我制作了一个 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/

相关文章:

ascii - 将 PI 数字转换为文本字符串

python - 使用 Mechanize 进行 Python 抓取脚本的 HTTP 错误 401

python - request.POST 中的每个值都是一个列表

python - 在 python 中的列表中附加列表中的项目时出现问题

algorithm - 在 Fortran 中使用蒙特卡罗方法估计 pi

linux - 在 pi 上流式传输视频的更有效方式

java - 在java代码中运行python脚本时出现问题

python - mongo 查询不返回结果

algorithm - 计算 Pi 的贝拉德算法

node.js - 找不到 module express,如何安装它以使其在全局范围内可用?