How to print floating point in scientific format?

Bengt Richter bokr at oz.net
Sun Aug 10 17:14:57 EDT 2003


On Sat, 09 Aug 2003 16:58:46 GMT, Alex Martelli <aleax at aleax.it> wrote:

>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).
>
>
OTOH, why not a sys.printhook ? There is a kind of precedent in

 >>> import sys
 >>> def dh(obj):
 ...     if isinstance(obj, (int, long, float)): return sys.__displayhook__('%e'%float(obj))
 ...     else:  return sys.__displayhook__(obj)
 ...
 >>> sys.displayhook = dh
 >>> 1
'1.000000e+000'
>>> _
'1.000000e+000'
>>> 2L
'2.000000e+000'
>>> 3.
'3.000000e+000'
>>> 1, 2L, 3.
(1, 2L, 3.0)

I didn't bother with recursive list and tuple mods. That would be up to the printhook user.
ISTM a printhook would be easy to implement and not disruptive overall, whatever silliness
it might inspire in particular individuals ;-)

Actually, I think there could even be some good use for it, since you could do things with
the object stream that you couldn't do by intercepting strings in sys.stdout.write.

Regards,
Bengt Richter




More information about the Python-list mailing list