我的代码返回了一些我不理解的东西。 该算法非常简单,它将X中的素数加到列表中,然后将所有数字相加。
如果X很小,累积循环和sum(list)函数给出了相同的答案,但是当X很大时......结果是不同的,我真的不明白为什么!
编辑:我用WinPython在3.3上遇到问题,我无法在股票分发中重现这个问题这是我的代码,没有is_prime函数,但是我尝试了测试的输出:
num_max=2*10**6
accu=[2]
total=2
#EDIT : here is the prime function
def is_prime(num):
if num%2 == 0 and num != 2 or num%3 == 0 and num != 3:
return False
for i in range(1, int((num**0.5+1)/6+1)):
if num%(6*i+1) == 0:
return False
if num%(6*i-1) == 0:
return False
return True
# END OF EDIT
for i in range(3, num_max, 2):
if is_prime(i) == True:
accu.append(i)
total += i
print(sum(accu)) # prints : 1179908154
print(total) # prints : 142913828922
# Test 1 --> The list "accu" seems to be created properly
tout=0
for num in accu:
tout+=num
print(tout) # prints : 142913828922
# Test 2 --> Also, I don't understand why sum() works on the first part of the list!
print(sum(accu[:1000])) # prints : 3682913
tot=0
for i in range(1000):
tot+=accu[i]
print(tot) # prints : 3682913
感谢您的帮助!
答案 0 :(得分:2)
您的设置正在将numpy.sum
导入到全局变量中,这会影响Python的builtins.sum
。
在这种情况下,np.sum
会调用ufunc
方法np.add.reduce
。在C API中,调用PyUFunc_GenericReduction
,调用PyArray_FromAny
将您的输入列表转换为ndarray
。当序列中的最大整数小于或等于long
时,此数组的数据类型设置为LONG_MAX
,与accu
的情况一样。随后,求和溢出,因为{32}和64位Windows上的LONG_MAX
都是2 ** 31 - 1
。例如:
>>> max(accu)
1999993
>>> np.sum(accu)
1179908154
>>> np.sum(accu, dtype='int32')
1179908154
>>> np.sum(accu, dtype='int64')
142913828922