# [Tutor] python precision output?

Eric Brunson brunson at brunson.com
Thu Dec 6 23:21:35 CET 2007

```Andre Walker-Loud wrote:
> Hi there,
>

Hi Andre,

First of all, please don't start a new thread by replying to an existing
original posting based on headers other than the Subject.  :-)

I don't think you'll ever get satisfactory precision using binary
floating point (the default for python's float type).  Take a look at
the decimal module, I believe it will give you much better results for

Here is the module documentation:
http://docs.python.org/lib/module-decimal.html

And an example of it's usage:

>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal("0.142857")
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal("0.1428571428571428571428571429")

Sincerely,
e.

> I am using python to do some scripting.  In particular, I am using it
> to run some jobs which require precision inputs.  I do this by having
> python write an input file, which I then feed to some other program.
>
> 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
>
> value = float( int(ai) * 6 * math.pi / (int(L)*int(T))
> replace = {'VALUE':str(value)}
> ini_file = open('generic_ini').read()
> f=open('my_input.xml','w')
> f.write(ini_file % replace)
> f.close()
>
> where, "ai", "L" and "T" are process dependent numbers defined in my
> script, and the output "my_input.xml", is just an xml file I later
> feed to another program, and this is why I replace 'VALUE' with a
> string.
>
> To reiterate, I need str(value) to be written to my file with 16
> digits of precision...???
>
>
> Thanks,
> Andre
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

```