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 ?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With