Search code examples
pythonvariablesprintingpi

Different number of digits in PI


I am a beginner in Python and I have a doubt regarding PI.

>>> import math
>>> p = math.pi
>>> print p
3.14159265359
>>> math.pi
3.141592653589793
  • Why are the two having different number of digits ?
  • How can I get the value of Pi up to more decimal places without using the Chudnovsky algorithm?

Solution

  • Why are the two having different number of digits ?

    One is 'calculated' with __str__, the other with __repr__:

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

    print uses the return value of __str__ of objects to determine what to print. Just doing math.pi uses __repr__.

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

    You can show more numbers with format() like so

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

    Where 20 is the number of decimals. More info in the docs