[Python-Dev] Rounding float to int directly ...

Ronald Oussoren ronaldoussoren at mac.com
Thu Aug 3 22:12:11 CEST 2006


On Aug 3, 2006, at 9:43 PM, Nick Maclaren wrote:

> Ka-Ping Yee <python-dev at zesty.ca> wrote:
>>
>> That's my experience as well.  In my opinion, the purpose of round()
>> is most commonly described as "to make an integer".  So it should
>> yield an integer.
>
> Grrk.  No, that logic is flawed.
>
> There are algorithms where the operation of rounding (or truncation)
> is needed, but where the value may be larger than can be held in an
> integer, and that is not an error.

Is that really true for python? Python integers are unbounded in  
magnitute, they are not the same as int or long in C, therefore any  
float except exceptional values like NaN can be converted to an  
integer value. The converse is not true, python integers can contain  
values that are larger than any float (aka C's double).

 >>> v = 1e200
 >>> int(v)
999999999999999969733122212510361659474503275455023626482417509503468484 
355540755341963384047062518680275124159738824081821357343682784846393850 
41047239877871023591066789981811181813306167128854888448L
 >>> type(v)
<type 'float'>
 >>> t = int(v)
 >>> t ** 2
999999999999999939466244425020724235032897553743712247233978162062705420 
868772363027380308001932133054230558394675289323324880702327952854432161 
552216024892912466614409626956153314556116473848998339762109232220813863 
099472521374735119038509661875525607726747258646821773646868361139842288 
412173261267039669530389442594522433115448347796339690544576171593343952 
0020822843337114038314499908946523848704L
 >>> float(t**2)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to float


Ronald
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2157 bytes
Desc: not available
Url : http://mail.python.org/pipermail/python-dev/attachments/20060803/5e233fa2/attachment.bin 


More information about the Python-Dev mailing list