-1

If I run the following code:

print math.pi, "******", 3.141592653589793

it outputs:

3.14159265359 ****** 3.14159265359

Why is the value being rounded? If I want a more precise value for Pi how would I go about getting it?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

1 Answers1

3
>>> print '%d'%math.pi
3
>>> print '%f'%math.pi
3.141593
>>> print '%.10f'%math.pi
3.1415926536
>>> print '%.20f'%math.pi
3.14159265358979311600
>>> print '%.30f'%math.pi
3.141592653589793115997963468544

You could use one of the above to get more digits after the comma printed. When doing calculations, Python use all the digits, but when printing them, Python uses either the default number of digits after comma, or the specified number of digits.

Your hardcoded number may get more digits when printed like this:

>>> print '%.20f'%3.141592653589793
3.14159265358979311600

As you can see the numbers are not 100% equals, the last digits are different. Is if given by the way floating point number are represented in computer memory.

Mihai Hangiu
  • 588
  • 4
  • 13
  • Ahhh - that was totally it. Thanks! – Abe Miessler Aug 02 '15 at 05:35
  • You don't happen to know if there is a way to set this globally do you? So that I don't have to do it with every print statement? – Abe Miessler Aug 02 '15 at 05:40
  • I do not know. But my intuition says: it is not possible. Personally I always explicitly specify the number of digits after the comma for float numbers, it is safer like this. We should get used with the fact that print displays a representation of the object (i.e. of the float number) and not the object itself. – Mihai Hangiu Aug 02 '15 at 06:17