[Pyrex] Basic Pyrex question
Matt Hammond
matt.hammond at rd.bbc.co.uk
Fri May 16 18:58:21 CEST 2008
To the best of my knowledge, on most common 32bit processor
architectures/environments/compilers these days, a long and int are both
the same size - 32bits (both wrap at just over +2000000000)
I believe python's built in integer support these days automatically
transparently starts using a data type capable of handling larger values
when the value reaches the threshold of needing it - hence the first of
your two examples still works.
Matt
On Fri, 16 May 2008 17:25:30 +0100, Rick Muller <rpmuller at gmail.com> wrote:
> Ah, makes sense. If I do:
>
> def sumpairs(l):
> cdef int i, j
> s = 0
> for i in xrange(len(l)):
> for j in xrange(i):
> s += l[i]*l[j]
> return s
>
> it gives the correct result. Oddly enough,
>
> def sumpairs(l):
> cdef int i, j
> cdef long s
> s = 0
> for i in xrange(len(l)):
> for j in xrange(i):
> s += l[i]*l[j]
> return s
>
> doesn't work.
>
> On Fri, May 16, 2008 at 10:21 AM, Matt Hammond
> <matt.hammond at rd.bbc.co.uk>
> wrote:
>
>> pyrex compiles down to C and the integer data type in C is probably
>> 32bit
>> on your platform. That means it can hold a values over the range +/-
>> 2000000000 roughly. The result of the calculation you issue is
>> substantially
>> larger than that, so the maths fails as the value probably simply wraps
>> back
>> round when it reaches the limit.
>>
>> regards
>>
>>
>> Matt
>>
>>
>> On Fri, 16 May 2008 17:12:43 +0100, Rick Muller <rpmuller at gmail.com>
>> wrote:
>>
>> I'm just learning Pyrex, and am making a mistake somewhere. I wanted to
>>> play
>>> with the simple function:
>>>
>>> def fastsumpairs(l):
>>> s = 0
>>> for i in xrange(len(l)):
>>> for j in xrange(i):
>>> s += l[i]*l[j]
>>> return s
>>>
>>> The first time through, the python and pyrex versions of this routine
>>> gave
>>> the same result, and the pyrex version was about 30% faster. Sweet.
>>>
>>> timeit(sumpairs(range(1,1000)): 0.202557 seconds
>>> 124583708250
>>> timeit(fastsumpairs(range(1,1000)): 0.155977 seconds
>>> 124583708250
>>>
>>> Now I tried to modify the code to tell it that s,i,j were ints:
>>>
>>> def fastsumpairs(l):
>>> cdef int s, i, j
>>> s = 0
>>> for i in xrange(len(l)):
>>> for j in xrange(i):
>>> s += l[i]*l[j]
>>> return s
>>>
>>>
>>> timeit(sumpairs(range(1,1000)): 0.202557 seconds
>>> 124583708250
>>> timeit(fastsumpairs(range(1,1000)): 0.069682 seconds
>>> 29656666
>>>
>>> So the function is now much faster, but it gives the wrong results. Any
>>> hints as to why?
>>>
>>>
>>
>>
>> --
>> | Matt Hammond
>> | Research Engineer, FM&T, BBC, Kingswood Warren, Tadworth, Surrey, UK
>> | http://www.bbc.co.uk/rd/
>>
>
>
>
--
| Matt Hammond
| Research Engineer, FM&T, BBC, Kingswood Warren, Tadworth, Surrey, UK
| http://www.bbc.co.uk/rd/
More information about the Pyrex
mailing list