How to print floating point in scientific format?

Alex Martelli aleax at aleax.it
Sat Aug 9 18:58:46 CEST 2003


sdhyok wrote:

> I want to change the DEFAULT behavior of python
> to print out all floating points in scientific format?
> For instance,
> 
>>x=0.01
>>print x
> 1.000000E-2 #Like print "%E"%x
> 
> How can I do it?

You need to download Python's sources, modify them, and build a modified
Python interpreter and libraries that impose the behavior you want rather
than what the normal Python interpreter and libraries do.

Specifically, look at function format_float, line 233 of file
Objects/floatobject.c in the current 2.3 maintenance branch for example.
Currently it formats the float with "%.*g" [variable precision passed
in as an argument to format_float]; if you want to use a different C level
format string, that string is the one you need to change.

Of course, that's likely to break some of the tests in Python's unit-tests
suite, so you'll probably want to modify those, too.  And then, you get to
maintain your "slightly divergent" Python yourself forevermore.  I do not
think there is much likelihood that a patch in this regard would be
accepted in the Python core, even if you made it flexible enough to keep
the current behavior by default and change it only upon specific request
(e.g., use a variable string for the format, and let the Python coder
modify the letter in it, only, keeping "%.*g" as the default but letting
the 'g' be changed) -- such "big global" settings, which would let one
idiosyncratic library module modify Python behavior enough to break other
innocent modules, are looked at with disfavour, for reasons that should
be obvious (each and every such 'big global' _damages_ Python's suitability
for writing very large, multi-authors applications -- that suitability is
currently very high, and _extremely_ convincing arguments would need to
be brought to bear in order to convince Guido to deliberately lower it).


Alex





More information about the Python-list mailing list