Kshitij Saraogi
Kshitij Saraogi

Reputation: 7619

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

Upvotes: 4

Views: 714

Answers (2)

gustafbstrom
gustafbstrom

Reputation: 1933

The print function rounds off the float to some extent. You can change how much, using:

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

In this particular case:

print "%1.11f" % math.pi

Upvotes: 3

Tim
Tim

Reputation: 43344

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

Upvotes: 14

Related Questions