[Python-Dev] Proposal: make float.__str__ identical tofloat__repr__ in Python 3.2

Michael Foord fuzzyman at voidspace.org.uk
Thu Jul 29 23:53:01 CEST 2010


On 29/07/2010 22:37, Robert Brewer wrote:
> Mark Dickinson wrote:
>    
>> Now that we've got the short float repr in Python, there's less value
>> in having float.__str__ truncate to 12 significant digits (as it
>> currently does).  For Python 3.2, I propose making float.__str__ use
>> the same algorithm as float.__repr__ for its output (and similarly for
>> complex).
>>
>> Apart from simplifying the internals a little bit, one nice feature of
>> this change is that it removes the differences in formatting between
>> printing a float and printing a container of floats:
>>
>>      
>>>>> l = [1/3, 1/5, 1/7]
>>>>> print(l)
>>>>>            
>> [0.3333333333333333, 0.2, 0.14285714285714285]
>>      
>>>>> print(l[0], l[1], l[2])
>>>>>            
>> 0.333333333333 0.2 0.142857142857
>>
>> Any thoughts or comments on this?
>>
>> There's a working patch at http://bugs.python.org/issue9337
>>      
> Python 2.5.4 (r254:67916, Jan 20 2010, 21:44:03)
>    
>>>> float("0.142857142857") * 7
>>>>          
> 0.99999999999899991
>    
>>>> float("0.14285714285714285") * 7
>>>>          
> 1.0
>
> I've made a number of tools in the past that needed to round-trip a
> float through a string and back. I was under the impression that floats
> needed 17 decimal digits to avoid losing precision. How does one do that
> efficiently if neither str nor repr return 17 digits?
>    

Because every floating point number represents a range of values - and 
the new algorithm uses the shortest possible representation within that 
range of values that will return the same floating point number.

Mark did an excellent presentation on this at EuroPython and the slides 
are online:

http://www.slideshare.net/dickinsm/magical-float-repr

Michael Foord
>
> Robert Brewer
> fumanchu at aminus.org
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/fuzzyman%40voidspace.org.uk
>    


-- 
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/blog

READ CAREFULLY. By accepting and reading this email you agree, on behalf of your employer, to release me from all obligations and waivers arising from any and all NON-NEGOTIATED agreements, licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap, confidentiality, non-disclosure, non-compete and acceptable use policies (”BOGUS AGREEMENTS”) that I have entered into with your employer, its partners, licensors, agents and assigns, in perpetuity, without prejudice to my ongoing rights and privileges. You further represent that you have the authority to release me from any BOGUS AGREEMENTS on behalf of your employer.




More information about the Python-Dev mailing list