[Tutor] Loop comparison

Stefan Behnel stefan_ml at behnel.de
Sat Apr 17 11:07:32 CEST 2010


Dave Angel, 17.04.2010 10:47:
> Alan Gauld wrote:
>> "Lie Ryan" wrote
>>
>>>> A friend of mine suggested me to do the next experiment in python
>>>> and Java.
>>>> It's a simple program to sum all the numbers from 0 to 1000000000.
>>>>
>>>> result = i = 0
>>>> while i < 1000000000:
>>>> result += i
>>>> i += 1
>>>> print result
>>>>
>>>
>>> Are you sure you're not causing Java to overflow here? In Java,
>>> Arithmetic Overflow do not cause an Exception, your int will simply wrap
>>> to the negative side.
>>
>> Thats why I asked if he got a float number back.
>> I never thought of it just wrapping, I assumed it would convert to
>> floats.
>
> It's been years, but I believe Java ints are 64 bits, on a 32bit
> implementation. Just like Java strings are all unicode.

Java has a 32bit 'int' and a 64bit 'long'.

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html

Both will work just fine for 'i', but 'result' requires a 64 bit long:

    >>> 1000000000 < 2**31
    True
    >>> 2**31 < 499999999500000000 < 2**63
    True

Stefan



More information about the Tutor mailing list