python - 加速 scipy.integrate.quad()?

标签 python performance numpy integration numerical

我正在尝试加速以下计算积分和的代码。为了获得良好的准确性,我需要增加 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 

最佳答案

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

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

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

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

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

关于python - 加速 scipy.integrate.quad()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17198898/

相关文章:

Python - 数组中的字符串和数字,想要对行中的所有数值求和,并将值附加到行末尾

python - python中的复杂列表切片/索引

performance - 我的 Perl 脚本启动太慢,并且包含许多模块 - 我可以预编译它吗?

python - Pandas - 按日期对日内时间序列进行分组

python - 将 numpy 数组从 VBA 移动到 Python 并返回

python - Google App Engine : app. yaml 与 python 代码中的身份验证

python - 类和变量

Oracle 综合指数性能

c++ - 小数组的for循环?

python - 直观理解 Numpy nd 数组