我是Python的初学者,对于PI值有疑问。
>>> import math
>>> p = math.pi
>>> print p
3.14159265359
>>> math.pi
3.141592653589793
- 为什么它们的数字位数不同?
- 如何在不使用Chudnovsky算法的情况下得到更多小数位的Pi值?
我是Python的初学者,对于PI值有疑问。
>>> import math
>>> p = math.pi
>>> print p
3.14159265359
>>> math.pi
3.141592653589793
为什么这两个数的位数不同?
一个是使用__str__
计算的,另一个是使用__repr__
计算的:
>>> print repr(math.pi)
3.141592653589793
>>> print str(math.pi)
3.14159265359
print
使用对象的__str__
返回值来确定要打印的内容。只是直接使用math.pi
会使用__repr__
。
如何在不使用 Chudnovsky 算法的情况下获得更多小数位的 Pi 值?
您可以使用format()
显示更多数字,例如:
>>> print "pi is {:.20f}".format(math.pi)
pi is 3.14159265358979311600
20为小数点后的数字位数。更多信息请参考文档
str()
和 repr()
。 - Kshitij Saraogiprint
函数会在一定程度上对浮点数进行四舍五入。你可以使用以下方法来更改这个程度:
print "%1.<number>f" % math.pi
print "%1.11f" % math.pi