python - PI 的位数不同

标签 python variables printing pi

我是 Python 的初学者,我对 PI 有疑问。

>>> import math
>>> p = math.pi
>>> print p
3.14159265359
>>> math.pi
3.141592653589793
  • 为什么两者的位数不同?
  • 如何在不使用 Chudnovsky 算法的情况下将 Pi 的值计算到更多小数位?

最佳答案

Why are the two having different number of digits ?

一个是用__str__“计算”的,另一个是用__repr__计算的:

>>> print repr(math.pi)
3.141592653589793
>>> print str(math.pi)
3.14159265359

print 使用对象的 __str__ 的返回值来确定要打印的内容。只是做 math.pi 使用 __repr__

How can I get the value of Pi up to more decimal places without using Chudnovsky algorithm ?

你可以像这样用format()显示更多的数字

>>> print "pi is {:.20f}".format(math.pi)
pi is 3.14159265358979311600

其中 20 是小数位数。更多信息在 the docs

关于python - PI 的位数不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31263763/

相关文章:

找到小于 X 数的二的最大幂?

python - 如何以 Pythonic 方式将 "ABCD…"转换为 "CDEF…"?

variables - 无法在批处理文件中设置变量

javascript - 打印时字体颜色会改变

python 正则表达式 : inverse match at the end of the line

python - 在 python spyne 服务器中打印出整个 SOAP 请求

php - OOP 中的可变变量

azure - 如何在 Terraform 中验证 IP 地址?

python - 如何生成和打印文档(python)

在 C 中创建迭代数组并格式化电话号码的方法