1.向量加法:
(1)纯python代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
defpythonsum(n):
a =range(n)
b =range(n)
c = []
foriinrange(len(a)):
a[i] = i **2
b[i] = i **3
c.append(a[i] + b[i])
returnc
n =input('please give me an n value:')
c = pythonsum(n)
printc
注:这里使用raw_input 会报错
运行:
please give me an n value:5
[0, 2, 12, 36, 80]
(2)使用Numpy:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
importnumpy
defnumpysum(n):
a = numpy.arange(n) **2
b = numpy.arange(n) **3
c = a + b
returnc
n =input('please give me an n value:')
c =numpysum(n)
printc
运行:
please give me an n value:5
[ 02 12 36 80]
这里,使用numpy中的arange函数来创建包含0~n的整数的numpy数组(arange函数从numpy模块中导入)。
numpysum()函数的输出不包括逗号,因为,我们在这里使用的是numpy数组,而非python自身的list容器。numpy数组对象以专用数据结构来存储数值。
接下来的程序将以微妙的精度分别记录numpysum()和pythonsum()函数的耗时,还将输出向量相加之后最末的两个元素
#!/usr/bin/env python
# -*- coding:utf-8 -*-
importsys
importnumpyasnp
fromdatetimeimportdatetime
'''
put this command to run :
python numpy_practice.py n
'''
defnumpysum(n):
a = np.arange(n) **2
b = np.arange(n) **3
c = a + b
returnc
defpythonsum(n):
a =range(n)
b =range(n)
c = []
foriinrange(len(a)):
a[i] = i **2
b[i] = i **3
c.append(a[i] + b[i])
returnc
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
运行(python 文件名 n)(n为指定向量大小的整数) :
$ python2 numpy_practice.py 2000
The last 2 elements of the sum [7980015996, 7992002000]
PythonSum elapsed time in microseconds 1034
The last 2 elements of the sum [7980015996 7992002000]
NumPySum elapsed time in microseconds 271
$ python2 numpy_practice.py 3000
The last 2 elements of the sum [26955023996, 26982003000]
PythonSum elapsed time in microseconds 1661
The last 2 elements of the sum [26955023996 26982003000]
NumPySum elapsed time in microseconds 371
注:使用ipython ,在pylab模式下,ipython将自动导入scipy numpy和matplotlib模块
$ipython2 --pylab
在当前目录下,可以按照下面这样自运行python脚本
In [3]: %run -i numpy_practice.py 1000
%run的-d参数将开启ipdb调试器,键入c后,脚本开始逐行执行了,在ipdb提示符后键入quit可以关闭调试器
%run的-p参数对脚本进行性能分析
%hist命令可以查看命令行历史记录
网友评论