Lambda
Lambda

Reputation: 109

Cython different results

Why this function in cython returns different results for every run?

I passed in 50000 for test

cpdef int fun1(int num):
    cpdef int result
    cdef int x
    for x in range(num):
        result += x*x
    return result

edit: so now I changed it to long long result like this

cpdef long long fun1(int num):
   cdef long long result = 0
   cdef int x = 0
   for x in range(num):
       result += x*x
   return result

and it returns 25950131338936 but :) the python func

def pyfunc(num):
    result = 0
    for x in range(num):
        result += x * x
    return result

return 41665416675000

so hm so what is wrong?

Upvotes: 1

Views: 533

Answers (2)

user3504575
user3504575

Reputation: 534

There are probably two problems here. First, result should be initialized to zero. Secondly, the result is the sum of all integers squared from 0 to 50 000 (non-inclusive)

enter image description here

The problem is that the storage type int cannot fit such a big number. Try using a larger storage type like long long and it will work. The maximum value a 32-bit integer can hold is roughly 2^31. The maximum value a long long can hold is typically 2^63. Consult the C compiler on the system at hand to figure out the exact limits.

Upvotes: 4

Laurent LAPORTE
Laurent LAPORTE

Reputation: 23012

The cdef statement is used to declare C variables, either local or module-level.

So you need to set the initial value to the result variable. If you don’t, it gets what it found in memory at call time, which can be anything.

cpdef int fun1(int num):
cdef int result = 0
cdef int x
for x in range(num):
    result += x * x
return result

Upvotes: 0

Related Questions