PI 的位数不同

Different number of digits in PI

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

>>> import math
>>> p = math.pi
>>> print p
3.14159265359
>>> math.pi
3.141592653589793

print函数在一定程度上对浮点数进行了四舍五入。您可以更改多少,使用:

print "%1.<number>f" % math.pi

在这种特殊情况下:

print "%1.11f" % math.pi

Why are the two having different number of digits ?

一个是 'calculated' 和 __str__,另一个是 __repr__:

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

print 使用对象 __str__ 的 return 值来确定要打印的内容。只是做 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

中的更多信息