作为练习的一部分,我在Numpy中实现了一个多项式类。我还使用标准Python列表和循环创建了另一个类,我在下面添加了这个类。
class Polynomial: # Implemented with Numpy
'''
This class is implementing a polynomial.
Instance variable --> coefficients which contains the coeff of the polynomial.
Methods:
__init__ initializes the class.
__call__ returns value of the polynomial given value of x
derivative takes derivative of the polynomial and returns the new coefficients.
'''
def __init__(self, coefficients):
self.coefficients = coefficients
def __call__(self, x):
polynomial_value = 0
X = np.ones(len(self.coefficients))
X[1:] = x
return np.cumprod(X) @ self.coefficients
def derivative(self):
n = len(self.coefficients)
new_coeff = self.coefficients[1:] * np.cumsum(np.ones(n-1))
self.coefficients = new_coeff
return self.coefficients class Polynomial: # Implemented without Numpy
def __init__(self, coefficients):
self.coefficients = coefficients
def __call__(self, x):
polynomial_value = 0
for i in range(len(self.coefficients)):
polynomial_value += self.coefficients[i]*(x**i)
return polynomial_value
def derivative(self):
n = len(self.coefficients)
new_coeff=[]
for i in range(1,n): # Note we are dropping a0 and thus we
new_coeff.append(self.coefficients[i]*i) # are starting from 1
self.coefficients = new_coeff
return self.coefficients 我使用以下例程测试了这2段代码:
%%timeit
import random
#Runtime on polynomial class
N = 10000
for i in range(1,N):
coeff = np.random.randint(0, 100, size = 10)
my_poly = Polynomial(coeff)
x = random.randint(0,100)
my_poly(x)%%timeit
import random
#Runtime on polynomial class
N = 10000
for i in range(1,N):
coeff = random.sample(range(0, 100), 10)
my_poly = Polynomial(coeff)
x = random.randint(0,100)
my_poly(x)第一次实施时间(Numpy)为249 ms,第二次实施时间为153 ms。
为什么是这种情况?在定义类或测试类时,我是否错误地实现了矢量化?还是还发生了什么事?
发布于 2020-06-14 22:26:02
这是因为你这样做的小方程,只有10个系数。我运行了100个系数的代码(即一个99度的方程),而numpy的运行时间是250 ms,而Python列表的运行时间是8.23秒。希望这能消除你的疑虑
https://stackoverflow.com/questions/62378784
复制相似问题