numpy.sum 未返回预期值
numpy.sum not returning expected value
我正在解决项目欧拉问题。
'Find the sum of all the primes below two million'
我已经构建了一个我认为非常快的素数检查器 - 任何关于如何改进的建议也会很棒。
但是,我花了最后 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。
我正在解决项目欧拉问题。
'Find the sum of all the primes below two million'
我已经构建了一个我认为非常快的素数检查器 - 任何关于如何改进的建议也会很棒。
但是,我花了最后 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。