unusual exponential formatting puzzle

mensanator at aol.com mensanator at aol.com
Wed Sep 21 16:17:08 EDT 2005


mensanator at aol.com wrote:
> Neal Becker wrote:
> > Like a puzzle?  I need to interface python output to some strange old
> > program.  It wants to see numbers formatted as:
> >
> > e.g.: 0.23456789E01
> >
> > That is, the leading digit is always 0, instead of the first significant
> > digit.  It is fixed width.  I can almost get it with '% 16.9E', but not
> > quite.
> >
> > My solution is to print to a string with the '% 16.9E' format, then parse it
> > with re to pick off the pieces and fix it up.  Pretty ugly.  Any better
> > ideas?
>
> If you have gmpy available...
>
> >>> import gmpy
>
> ...and your floats are mpf's...
>
> >>> s = gmpy.pi(64)
> >>> s
> mpf('3.14159265358979323846e0',64)
>
> ...you can use the fdigits function
>
> >>> t = gmpy.fdigits(s,10,8,0,0,2)
>
> ...to create a seperate digit string and exponent...
>
> >>> print t
> ('31415927', 1, 64)
>
> ...which can then be printed in the desired format.
>
> >>> print "0.%sE%02d" % (t[0],t[1])
> 0.31415927E01

Unless your numbers are negative.

>>> print "0.%sE%02d" % (t[0],t[1])
0.-31415927E03

Drat. Needs work.



And does the format permit large negative exponents (2 digits + sign)?

>>> print "0.%sE%02d" % (t[0],t[1])
0.31415927E-13




More information about the Python-list mailing list