numerical integration python

爱⌒轻易说出口 提交于 2019-12-25 09:14:04

问题


I need to reduce the running time for quad() in python (I am integrating some thousands integrals). I found a similar question in here where they suggested to do several integrations and add the partial values. However that does not improve performance. Any thoughts? here is a simple example:

import numpy as np                      
from scipy.integrate import quad
from scipy.stats import norm
import time

funcB = lambda x: norm.pdf(x,0,1)

start = time.time()
good_missclasified,_ = quad(funcB, 0,3.3333)
stop = time.time()
time_elapsed = stop - start 
print ('quad : ' + str(time_elapsed))

start = time.time()
num = np.linspace(0,3.3333,10)
Lv = []
last, lastG = 0, 0
for g in num:
  Lval,x = quad(funcB, lastG, g)
  last, lastG = last + Lval, g
  Lv.append(last)
Lv = np.array(Lv)
stop = time.time()

time_elapsed = stop - start 
print ('10 int : ' + str(time_elapsed))
print(good_missclasified,Lv[9])

回答1:


quadpy (a project of mine) is vectorized and can integrate a function over many domains (e.g., intervals) at once. You do have to choose your own integration method though.

import numpy
import quadpy

a = 0.0
b = 1.0
n = 100
start_points = numpy.linspace(a, b, n, endpoint=False)
h = (b-a) / n
end_points = start_points + h
intervals = numpy.array([start_points, end_points])

scheme = quadpy.line_segment.gauss_kronrod(3)
vals = scheme.integrate(numpy.exp, intervals)
print(vals)
[0.10050167 0.10151173 0.10253194 0.1035624  0.10460322 0.1056545
 0.10671635 0.10778886 0.10887216 0.10996634 0.11107152 0.11218781
 0.11331532 0.11445416 0.11560444 0.11676628 0.1179398  0.11912512
 0.12032235 0.12153161 0.12275302 0.12398671 0.12523279 0.1264914
 0.12776266 0.1290467  0.13034364 0.13165362 0.13297676 0.1343132
 0.13566307 0.1370265  0.13840364 0.13979462 0.14119958 0.14261866
 0.144052   0.14549975 0.14696204 0.14843904 0.14993087 0.15143771
 0.15295968 0.15449695 0.15604967 0.157618   0.15920208 0.16080209
 0.16241818 0.16405051 0.16569924 0.16736455 0.16904659 0.17074554
 0.17246156 0.17419482 0.17594551 0.17771379 0.17949985 0.18130385
 0.18312598 0.18496643 0.18682537 0.188703   0.1905995  0.19251505
 0.19444986 0.19640412 0.19837801 0.20037174 0.20238551 0.20441952
 0.20647397 0.20854907 0.21064502 0.21276204 0.21490033 0.21706012
 0.21924161 0.22144502 0.22367058 0.22591851 0.22818903 0.23048237
 0.23279875 0.23513842 0.2375016  0.23988853 0.24229945 0.2447346
 0.24719422 0.24967857 0.25218788 0.25472241 0.25728241 0.25986814
 0.26247986 0.26511783 0.2677823  0.27047356]


来源:https://stackoverflow.com/questions/39678412/numerical-integration-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!