Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 677
Kshitij Saraogi Avatar asked Dec 02 '22 16:12

Kshitij Saraogi


2 Answers

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

like image 73
Tim Avatar answered Dec 05 '22 06:12

Tim


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
like image 41
gustafbstrom Avatar answered Dec 05 '22 07:12

gustafbstrom