操纵多项式积分Python

时间:2018-01-08 16:50:21

标签: python computer-science polynomials

我试图进行矢量化,这个等式使其更快(即不使用循环)这就是sslow反对sfast的想法。

mu2 = [1.0, 0.11264281499520618, 0.012799179048180226]
alpha = np.array([   52.64173932, -1016.96156872,  4514.08903276])
def sslow(alpha):
    t0 = time()
    u = lambda x: np.exp(-(1+np.poly1d(list(reversed(alpha)))(x)))
    k = sp.integrate.quad(lambda x: u(x), 1e-16, 1)[0]+np.dot(mu2,alpha),(time()-t0)
return k
def sfast(alpha):
    t0 = time()
    def int1(b):
        j = 1
        for q in range(0,len(alpha)):
            j = j + alpha[q]*(b**q)
        return np.exp(-j)
    ans, err = sp.integrate.quad(int1, 1e-16, 1)
    u = ans+np.dot(mu2,alpha);
    return u,(time()-t0)
t = []
r = int(1e3)
for d in range(0,r):
    t = (np.append(t,sslow(alpha)[1]))
print sum(t)/r
t = []
for d in range(0,r):
    t = (np.append(t,sfast(alpha)[1]))
print sum(t)/r

Here we can see "the result,time taken" of both methods

我完全错过了什么吗?有没有更好的方法来获得矢量和多项式基础之间的点积,然后进行积分?

1 个答案:

答案 0 :(得分:0)

你的功能中的点积很好。如果mualpha2只有三个条目,则显式计算可能会更快,因为np.dot会有轻微的开销,例如使用np.sum(mu * alpha)甚至alpha[0] * mu[0] + alpha[1] * mu[1] + alpha[2] * mu[2]。不漂亮,但我发现,对于非常小的计算,它优于numpy函数。

我修改了您的sslow功能,它比我机器上的sfast快两倍。随意添加明确的点积。

def sslow5(alpha):
    t0 = time.time()

    u = lambda x: np.exp(-(1 + (alpha[2]*x + alpha[1])*x + alpha[0]))

    k = quad(u, 1e-16, 1)[0] + np.dot(mu2, alpha),(time.time()-t0)
    return k

嗯,这只适用于程度非常低的程度,您可以明确说明等式(参见https://stackoverflow.com/a/24067326/7919597)。