Closed siyavashmoradi closed 11 months ago
@siyavashmoradi I cannot reproduce the error:
import time
# S = N * (N + 1) / 2
size: Static[int] = 128 # S > 64-bit integer
exp = 10
N = UInt[size](10 ** exp)
result = UInt[size](0)
st = time.time()
start = 1
stop = int(N + UInt[size](1))
for i in range(start, stop):
result += UInt[size](i)
et = time.time()
elapsed_time = et - st
print('Sum: ', result, str(result), len(str(result)))
print('Execution time:', elapsed_time, 'seconds')
# test result
test = N * (N + UInt[size](1)) # / 2 # do not use float
assert test == result * UInt[size](2)
prints:
Sum: 50000000005000000000 50000000005000000000 20
Execution time: 0 seconds
Python code to test result:
N = 10 ** 10
test = N * (N + 1) # / 2 # do not use float
print(test)
It's probably because I forgot to put the indent after the for loop, with the indent for the line "sum_x += I" you can probably reproduce the results
Also in the for loop if I put 10e+9 it works just fine, but if I go higher it gives wrong result
Codon integers are 64 bits by default, but the answer must be stored in at least 66 bit ints.
Codon integers are 64 bits by default, but the answer must be stored in at least 66 bit ints.
Thanks. didn't know it.
Yes, Codon integers by default are 64-bit ints. See https://docs.exaloop.io/codon/general/differences for how to use Python integers (with a warning; performance might suffer).
Here is a test with codon:
import time
st = time.time() sum_x = 0 for i in range(10000000000): sum_x += i time.sleep(3) print('Sum of first 10 bilion numbers is:', sum_x) et = time.time() elapsed_time = et - st print('Execution time:', elapsed_time, 'seconds')
Here is the result with python3:
python3 test.py Sum of first 10 bilion numbers is: 49999999995000000000 Execution time: 557.8164610862732 seconds
Here is the result with codon:
codon run -release test.py Sum of first 10 bilion numbers is: -5340232226128654848 Execution time: 3.00534 seconds
As you can see the answer with codon is completely wrong.