Underscores in Python numbers

D H x at y.z
Sun Nov 20 11:22:28 EST 2005


Steve Holden wrote:
> David M. Cooke wrote:
>> One example I can think of is a large number of float constants used
>> for some math routine. In that case they usually be a full 16 or 17
>> digits. It'd be handy in that case to split into smaller groups to
>> make it easier to match with tables where these constants may come
>> from. Ex:
>>
>> def sinxx(x):
>>     "computes sin x/x for 0 <= x <= pi/2 to 2e-9"
>>     a2 = -0.16666 66664
>>     a4 =  0.00833 33315
>>     a6 = -0.00019 84090
>>     a8 =  0.00000 27526
>>     a10= -0.00000 00239
>>     x2 = x**2
>>     return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10))))
>>
>> (or least that's what I like to write). Now, if I were going to higher
>> precision, I'd have more digits of course.
>>
> Right, this is clearly such a frequent use case it's worth changing the 
> compiler for.

Yes it is.
In that one example he used digit grouping 5 more times than I've
used lambda in my life.  Remember people use python as a data format as 
well (see for example JSON).
It's a simple harmless change to the parser: ignore underscores or 
spaces in numeric literals.  As others have mentioned, Ruby supports
this already, as do Ada, Perl, ML variants, VHDL, boo, nemerle, and others.



More information about the Python-list mailing list