我正在解决项目欧拉问题。
“求 200 万以下所有素数的和”
我已经构建了一个主要检查器,我认为它非常快 - 任何有关如何改进的建议也很棒。
但是,我在过去 30 分钟里发现 np.sum 没有返回正确的值。这是我的代码:
import numpy as np
def isprime(num, primelist):
#Give primelist it's first value if none exist
if len(primelist) == 0:
primelist.append(num)
return True
for primes in primelist:
#Only need to iterate up to square root of num to test primality
if primes <= math.sqrt(num):
#If any number is evenly divisble (remainder = 0) the num is not prime
if num % primes == 0:
#print('non-prime')
return False
break
#If we have iterated through all primes <= sqrt of num, num is prime
else:
primelist.append(num)
#print('prime')
return True
break
lim = 2000000
n = 3
primelist = [2]
while primelist[-1] <= lim:
isprime(n, primelist)
n += 1
if primelist[-1] > lim: primelist = primelist[:-1]
primearray = np.asarray(primelist)
print(np.sum(primearray))
sum = 0
for i in primelist:
sum = sum + i
print(sum)
我想这也可能是 np.asarray 不起作用,而不是 np.sum
我已经迭代了原始列表来测试返回的值 numpy。
numpy 总和 = 1179908154
迭代总和 = 142913828922
大 100 倍以上。请问我哪里错了!!
最佳答案
我的猜测是您使用的是 Windows,其中 numpy 中整数的默认大小是 32 位。 np.sum(primelist)
使用 32 位整数计算总和,并且总和溢出。您可以通过计算(使用 Python 整数)142913828922 % (2**31)
来验证这一点:
In [18]: s = 142913828922
In [19]: s % (2**31)
Out[19]: 1179908154
这是您使用 numpy.sum(primelist)
获得的值。
您可以通过将 primelist
显式转换为 64 位无符号整数数组,然后计算其总和来避免该问题(或至少将其推迟到 64 位整数溢出):
np.array(primelist, dtype=np.uint64).sum()
或者在处理非常大的整数时不要使用 numpy。
关于python - numpy.sum 未返回预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44743063/