[SciPy-user] force to scientific output

John Hunter jdhunter at ace.bsd.uchicago.edu
Mon Oct 17 09:26:51 CDT 2005

>>>>> "Christian" == Christian Meesters <meesters at uni-mainz.de> writes:

    Christian> Hi This is totally off-topic, but I guess chances are
    Christian> that some of you know an answer.  I need to write an
    Christian> output file for a command line tool which requires a
    Christian> column of floats - in so called scientific notation
    Christian> (4.23e-2 instead of 0.0423). Is there a way to dump
    Christian> numbers like this to a file?

You need to use the '%e' format string.  

    In [8]: '%e'%1.2
    Out[8]: '1.200000e+00'

You can control the precision

    In [11]: '%.2e'%1.2
    Out[11]: '1.20e+00'

You can convert an array and then write it as a list of new lines with
list comprehensions

    In [15]: s = '\n'.join(['%e'%val for val in rand(5)])

    In [16]: s
    Out[16]: '5.805749e-01\n8.112261e-01\n5.021213e-01\n5.141693e-01\n9.689626e-02'

or use a helper function for this.  matplotlib has save

  save('test3.out', x, fmt='%1.4e')  # use exponential notation

and scipy has scipy.io.write_array, which is crashing when I test with
the new scipy.  This could be me, since I rarely use this function, or
perhaps a bug in the scipy migration(?)

In [2]: import scipy.io

In [3]: fh = file('somefile.dat', 'w')

In [4]: x = scipy.array([1,2,3])

In [5]: scipy.io.write_array(fh, x, precision='%e')
Traceback (most recent call last):
  File "<console>", line 1, in ?
  File "/usr/lib/python2.4/site-packages/scipy/io/array_import.py", line 462, in write_array
    ss = suppress_small)
  File "/usr/lib/python2.4/site-packages/scipy/io/array_import.py", line 393, in str_array
    thistype = arr.typecode()
AttributeError: 'scipy.ndarray' object has no attribute 'typecode'

More information about the SciPy-user mailing list