unusual exponential formatting puzzle

Michael Spencer mahs at telcopartners.com
Wed Sep 21 19:31:12 EDT 2005


Michael Spencer 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?
>>
>>
> 
> Does this do what you want?

Not, if the input is 0 or 1.  Here's a correction, with a more comprehensive test

from math import log10, modf, fabs

def format(n, mantplaces = 9, expplaces = 2):
     """Formats n as '0.mmmmmmmmmEee'"""
     if n:
         sign, absn = n/fabs(n), fabs(n)
         f, i = modf(log10(absn))
         mant, exp = sign * 10** (f - (f>=0)), i + (f>=0)
     else:
         mant, exp = 0, 0
     return "%.*fE%0*d" % (mantplaces, mant, expplaces, exp)

def test_format(N = 10000, step = 1):
     """Verifies format(n) and format(1/n) for -N < n < N"""
     assert format(0,9) == '0.000000000E00'
     assert format(0, 7, 3) == '0.0000000E000'

     def verify(n):
         DIGITS = '123456789'
         try:
             f = format(n)
             assert round(float(format(n)),6) == round(n, 6)
             assert f[0] == "-" and f[3] in DIGITS or f[2] in DIGITS
         except AssertionError:
             raise AssertionError("Failed on: %f, formatted as %s" % (n, f))

     for  n in xrange(-N, N, step):
         if n:
             verify(n)
             verify(1.0/n)


Michael




More information about the Python-list mailing list