【问题标题】:speeding up scipy.integrate.quad()?加速 scipy.integrate.quad()?
【发布时间】:2013-06-16 10:33:08
【问题描述】:

我正在尝试加快计算积分总和的以下代码。为了获得良好的准确性,我需要增加 L_max 但这也会使执行时间更长。下面的具体情况计算概率曲线的 0.999999,大约需要 65 秒。我听说过 cython 及其加速代码的能力,但我不知道如何使用它或在这种情况下它如何提供帮助。有什么想法吗?

import math
from scipy import integrate
import numpy
from decimal import *
import time

start_time=time.time()
getcontext().prec=100
################################
def pt(t):
    first_term=math.exp(-lam*t)*((0.0001*I)**ni)*(t**(ni-1))*math.exp(-(0.0001*I)*t)/(math.factorial(ni-1))
    sum_term=0.0
    i=0
    while i<ni:
        sum_term=sum_term+((0.0001*I)**i)*(t**(i))*math.exp(-(0.0001*I)*t)/(math.factorial(i))
        i=i+1
    sum_term=lam*math.exp(-lam*t)*sum_term
    total=first_term+sum_term
    return total
#################################
def pLgt(t):
    return Decimal(((Decimal((0.0001*O)*t))**Decimal(L))*Decimal(math.exp(-(0.0001*O)*t)))/Decimal((math.factorial(L)))
######################################
def pL_t(t):
    return (pLgt(t))*Decimal(pt(t))
################################
lam=0.0001
beta=0.0001
ni=10
I=5969
O=48170
L_max=300.0
L=0.0
sum_term=0.0
sum_probability=0.0
while L<L_max:
    probability=(integrate.quad(lambda t: pL_t(t),0,800))[0]
    sum_probability=sum_probability+probability
    sum_term=sum_term+L*probability
    L=L+1.0
print time.time()-start_time
print sum_probability
print sum_term
print (sum_term-1)*0.46+6.5 

【问题讨论】:

标签: python performance numpy integration numerical


【解决方案1】:

使用 Decimal 进行计算可能会大大减慢您的速度,而不会带来任何好处。正如 Kozyarchuk 在 Stack Overflow here 上指出的那样,十进制计算比浮点数慢得多,大约慢 100 倍。在 Numpy 数组中使用 Decimal 类型会使您无法从 Numpy 中获得速度优势。

同时,我不清楚 scipy.integrate.quad 的结果实际上是否达到您想要的精度水平;如果您确实需要任意精度,则可能必须从头开始编写正交代码。

如果您确实需要使用十进制数字,至少缓存这些数字的十进制表示将为您提供一些速度优势。也就是说,使用

O=Decimal(48170)
L=Decimal(0.0)

告诉 pLgt 只使用 O 和 L,会更快。

【讨论】:

    【解决方案2】:

    pL_t 函数看起来像伽马分布的总和,在这种情况下,您应该能够将积分评估为部分不完全伽马函数的总和:http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.gdtr.html#scipy.special.gdtr

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多