[Tutor] How does the interpreter determine how many decimal places to display for a float?

Peter Otten __peter__ at web.de
Sun May 16 11:34:11 EDT 2021


On 15/05/2021 20:45, boB Stepp wrote:
> On Sat, May 15, 2021 at 3:38 AM Peter Otten <__peter__ at web.de> wrote:
>>
>> On 15/05/2021 05:29, boB Stepp wrote:
>>
>>> How does >= Python 3.1 determine the "shortest of these"?
>>
>> This is an interesting question...
> 
> More interesting than I suspected based on what you have uncovered.
> 
>> A little digging in the Python source turns up
>>
>> https://github.com/python/cpython/blob/main/Python/dtoa.c
> 
> How did you ever suspect to look here?

Actually I didn't. In a local copy of the CPython source I looked into

Objects/floatobject.c

for the repr() implementation, found it was basically

PyOS_double_to_string()

searched the source tree for its implementation which is in

Python/pystrtod.c

Getting here should be possible with only cursory knowledge of C, an 
editor, and grep.

While the last step may be a bit harder the general recipe is very 
simple: start a some point and jump from function call to function 
definition until you have found the actual operation you are interested 
in. You can professionalize this and use a debugger or an IDE feature, 
but just grep -- and print() when you are really lost -- is not much slower.


   "dtoa" = ?  Decimal to ASCII?
> I would have never suspected I should look here.
> 
> I have not studied C.  Looking over the referenced source code,  why
> do C programmers use such cryptic acronyms for their naming?

As Alan hints, the short "cryptic" names are likely the old ones, and 
there are only a few ones that are or were heavily used. Most of the 
functions in the CPython source have descriptive names. Because there 
are no namespaces names even tend to get too long for readable code.


I looked
> up the C standard for naming and there is no prohibition on using
> descriptive names.  The naming used in this file is reminiscent of my
> distant FORTRAN days.  Ugh!
> 
>> Does that answer your question? Well, it didn't help me, so I looked for
>> the original code and found what seems to be the corresponding paper
>>
>> David M. Gay:
>> Correctly Rounded Binary-Decimal and Decimal-Binary Conversion
>> https://ampl.com/REFS/rounding.pdf
>>
>> which in turn leads to
>>
>> Guy L. Steele Jr., Jon L White:
>> How to Print Floating-Point Numbers Accurately
>>
>> https://lists.nongnu.org/archive/html/gcl-devel/2012-10/pdfkieTlklRzN.pdf
>>
>>
>> Hope that helps ;)
> 
> Looks like some light after dinner reading.  ~(:>))
> 
> Thanks!
> boB Stepp
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 




More information about the Tutor mailing list