gpt4 book ai didi

python - numpy 初学者数组普通 python 与 numpy 向量 : faulty results

转载 作者:太空宇宙 更新时间:2023-11-03 19:13:41 26 4
gpt4 key购买 nike

我对 NumPy 完全陌生,并尝试了教科书代码。不幸的是,在一定规模的计算下,NumPy 结果会搞砸。代码如下:

import sys
from datetime import datetime
import numpy

def pythonsum(n):
a = range(n)
b = range(n)
c = []
for i in range(len(a)):
a[i] = i**2
b[i] = i**3
c.append(a[i]+b[i])
return c

def numpysum(n):
a = numpy.arange(n) ** 2
b = numpy.arange(n) ** 3
c = a + b
return c

size = int(sys.argv[1])
start = datetime.now()
c=pythonsum(size)
delta = datetime.now()-start
print "The last 2 elements of the sum",c[-2:]
print "PythonSum elapsed time in microseconds", delta.microseconds
start = datetime.now()
c=numpysum(size)
delta = datetime.now()-start
print "The last 2 elements of the sum",c[-2:]
print "NumPySum elapsed time in microseconds", delta.microseconds

当大小 >= 1291 时结果为负我正在使用 python 2.6、MacOSX 10.6、NumPy 1.5.0有什么想法吗?

最佳答案

开始 Numpy 1.5 ?

“实践时刻 - 添加向量”中的介绍性示例只能在允许长整数的 64 位平台上运行。否则会返回错误结果:

The last 2 elements of the sum [-2143491644 -2143487647]

为了解决这个问题,将幂函数中的整数转换为 float ,这样浮点值就会被转发。结果:速度提高了 10 倍

$ python vectorsum.py 1000000

The last 2 elements of the sum [9.99995000008e+17, 9.99998000001e+17]

PythonSum elapsed time in microseconds 3 59013

The last 2 elements of the sum [ 9.99993999e+17 9.99996999e+17]

NumPySum elapsed time in microseconds 0 308598

更正的示例:

import sys

from datetime import datetime

import numpy

def numpysum(n):

a = numpy.arange(n) ** 2.

b = numpy.arange(n) ** 3.

c = a + b

return c

def pythonsum(n): a = range(n)

  b = range(n)

c = []

for i in range(len(a)):

a[i] = i ** 2. # notice the dot (!)

b[i] = i ** 3.

c.append(a[i] + b[i])

return c

size = int(sys.argv[1])

start = datetime.now()

c = pythonsum(size)

delta = datetime.now() - start

print "The last 2 elements of the sum", c[-2:]

print "PythonSum elapsed time in microseconds", delta.seconds, delta.microseconds

start = datetime.now()

c = numpysum(size)

delta = datetime.now() - start

print "The last 2 elements of the sum", c[-2:]

print "NumPySum elapsed time in microseconds", delta.seconds, delta.microseconds

代码可以在此处的pastebin中找到http://paste.ubuntu.com/1169976/

关于python - numpy 初学者数组普通 python 与 numpy 向量 : faulty results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12138782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com