How to print floating point in scientific format?

David M. Cooke cookedm+news at physics.mcmaster.ca
Sun Aug 10 21:18:13 EDT 2003


At some point, Alex Martelli <aleax at aleax.it> wrote:
> sdhyok wrote:
>
>> As you recommend, I won't modify the default behavior of python.
>> But, still I need a better treatment of python on arrays.
>
> You seem to be focused on readable display of arrays (quite an
> unusual focus for scientific programming).  So, worst case, it's trivial 
> to write a general purpose function that takes an array of ANY size
> and rank and emits it in the way you prefer -- easier than in any
> other language commonly used for scientific programming.

With Numeric at least, you can set globally the functions used for
str() and repr() on arrays, giving exactly this, without requiring a
separate function for representations. Have a look at Numeric.py,
multiarray.set_string_function(), and ArrayPrinter.py from the Numeric
distribution.

The simple way of controlling output with Numeric is to use the
variables sys.output_line_width, sys.float_output_precision and
sys.float_output_supress_small (if true, replace in the output numbers that
are much smaller than the rest with zero, which is very nice when most of
your numbers are 1.0, and you've got some annoying 1.8342e-17 that you want
to ignore). These are added by Numeric to the sys module.

With numarray, you could subclass the array object, write your own
__str__ and __repr__ methods, and use that instead.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca




More information about the Python-list mailing list