您的位置:首页 > 产品设计 > UI/UE

《NumPy Beginner's Guide》笔记Chapter1

2016-03-08 23:23 309 查看
# -*- coding: utf-8 -*-
#日期 =  23:33

"""
1.
Imagine that we want to add two vectors called a and b
The vector a holds the squares of integers 0 to n, for instance, if n is equal to 3,
then a is equalto 0, 1, or 4. The vector b holds the cubes of integers 0 to n, so if
n is equal to 3, then the vector b is equal to 0, 1, or 8.

"""

#plain Python 实现
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

#numpy 实现
import numpy as np

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

import time
tic = time.time()
for i in range(10000):   #循环10000次
c = pythonsum(1000)
toc = time.time()
print("The execute time of python is %f s" % (toc - tic))

tic = time.time()
for i in range(10000):   #循环10000次
c = numpysum(1000)
toc = time.time()
print("The execute time of numpy is %f s" % (toc - tic))

"""
输出:
The execute time of python is 3.842000 s
The execute time of numpy is 0.916000 s

"""
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  numpy