[Tutor] python precision output?

wesley chun wescpy at gmail.com
Thu Dec 6 23:26:44 CET 2007


> The problem I am having is getting python to write number into this
> input file, keeping 16 digits of precision.  I have played around
> interactively, and see that python default prints 17 digits of
> precision to the screen, but when I use a replace command to write
> into the input file, it only prints 12 digits of precision.  The
> relevant snipit of my script is
>        :
> To reiterate, I need str(value) to be written to my file with 16
> digits of precision...???

if you want accuracy and are willing to sacrifice the total range of
numbers that Python's IEEE754 double-precision floats give you, then
use the decimal.Decimal class instead -- better precision, smaller
range.

however, if you wish to stick with floats, use the string format
operator and tell it you want 17 places after the decimal point:

>>> x=7./13
>>> x
0.53846153846153844
>>> str(x)
'0.538461538462'
>>> '%.17f' % x
'0.53846153846153844'

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list